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.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;
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;
51 import java.util.regex.Pattern;
54 * Responsible for listening for notifications from netconf containing latest
55 * committed configuration that should be persisted, and also for loading last
59 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
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;
65 private final InetSocketAddress address;
66 private final EventLoopGroup nettyThreadgroup;
68 private NetconfClientDispatcher netconfClientDispatcher;
69 private NetconfClient netconfClient;
71 private final Persister persister;
72 private final MBeanServerConnection mbeanServer;
75 private final ObjectName on = DefaultCommitOperationMXBean.objectName;
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;
81 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
82 MBeanServerConnection mbeanServer, Pattern ignoredMissingCapabilityRegex) {
83 this(persister, address, mbeanServer, DEFAULT_TIMEOUT, ignoredMissingCapabilityRegex);
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;
94 this.nettyThreadgroup = new NioEventLoopGroup();
95 this.ignoredMissingCapabilityRegex = ignoredMissingCapabilityRegex;
98 public void init() throws InterruptedException {
99 Optional<ConfigSnapshotHolder> maybeConfig = loadLastConfig();
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());
108 final String configSnapshot = maybeConfig.get().getConfigSnapshot();
109 logger.trace("Pushing following xml to netconf {}", configSnapshot);
111 pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
112 } catch(ConflictingVersionException e) {
113 closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
116 } catch (SAXException | IOException e) {
117 throw new IllegalStateException("Unable to load last config", e);
120 throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
121 + maxAttempts, lastException);
124 // this ensures that netconf is initialized, this is first
126 // this means we can register as listener for commit
127 registerToNetconf(Collections.<String>emptySet());
129 logger.info("No last config provided by backend storage {}", persister);
131 registerAsJMXListener();
134 private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
136 Set<String> currentCapabilities = Sets.newHashSet();
138 // TODO think about moving capability subset check to netconf client
139 // could be utilized by integration tests
141 long pollingStart = System.currentTimeMillis();
146 long deadline = pollingStart + timeout;
147 while (System.currentTimeMillis() < deadline) {
149 netconfClientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
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();
158 currentCapabilities = netconfClient.getCapabilities();
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;
169 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
171 closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
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);
183 private static void closeClientAndDispatcher(Closeable client, Closeable dispatcher) {
184 Exception fromClient = null;
187 } catch (Exception e) {
192 } catch (Exception e) {
193 if (fromClient != null) {
194 e.addSuppressed(fromClient);
197 throw new RuntimeException("Error closing temporary client ", e);
202 private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
203 for (String exCap : expectedCaps) {
204 if (currentCapabilities.contains(exCap) == false)
210 private void registerAsJMXListener() {
212 mbeanServer.addNotificationListener(on, this, null, null);
213 } catch (InstanceNotFoundException | IOException e) {
214 throw new RuntimeException("Cannot register as JMX listener to netconf", e);
219 public void handleNotification(Notification notification, Object handback) {
220 if (notification instanceof NetconfJMXNotification == false)
223 // Socket should not be closed at this point
224 // Activator unregisters this as JMX listener before close is called
226 logger.debug("Received notification {}", notification);
227 if (notification instanceof CommitJMXNotification) {
229 handleAfterCommitNotification((CommitJMXNotification) notification);
230 } catch (Exception e) {
231 // TODO: notificationBroadcast support logs only DEBUG
232 logger.warn("Exception occured during notification handling: ", e);
236 throw new IllegalStateException("Unknown config registry notification type " + notification);
239 private void handleAfterCommitNotification(final CommitJMXNotification notification) {
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);
249 private Optional<ConfigSnapshotHolder> loadLastConfig() {
250 Optional<ConfigSnapshotHolder> maybeConfigElement;
252 maybeConfigElement = persister.loadLastConfig();
253 } catch (IOException e) {
254 throw new RuntimeException("Unable to load configuration", e);
256 return maybeConfigElement;
259 private synchronized void pushLastConfig(Element xmlToBePersisted) throws ConflictingVersionException {
260 logger.info("Pushing last configuration to netconf");
261 StringBuilder response = new StringBuilder("editConfig response = {");
264 NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
266 // sending message to netconf
267 NetconfMessage responseMessage = netconfClient.sendMessage(message, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
269 XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
270 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
271 element = element.getOnlyChildElement();
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);
278 element = XmlElement.fromDomDocument(responseMessage.getDocument());
279 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
280 element = element.getOnlyChildElement();
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);
290 static void checkIsOk(XmlElement element, NetconfMessage responseMessage) throws ConflictingVersionException {
291 if (element.getName().equals(XmlNetconfConstants.OK)) {
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);
303 throw new IllegalStateException("Can not load last configuration, operation failed: "
304 + XmlUtil.toString(responseMessage.getDocument()));
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()));
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);
316 Document doc = XmlUtil.readXmlToDocument(stream);
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));
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);
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);
342 public synchronized void close() {
343 // TODO persister is received from constructor, should not be closed
347 } catch (Exception e) {
348 logger.warn("Unable to close config persister {}", persister, e);
351 if (netconfClient != null) {
353 netconfClient.close();
354 } catch (Exception e) {
355 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
359 if (netconfClientDispatcher != null) {
361 netconfClientDispatcher.close();
362 } catch (Exception e) {
363 logger.warn("Unable to close connection to netconf {}", netconfClientDispatcher, e);
368 nettyThreadgroup.shutdownGracefully();
369 } catch (Exception e) {
370 logger.warn("Unable to close netconf client thread group {}", netconfClientDispatcher, e);
373 // unregister from JMX
375 if (mbeanServer.isRegistered(on)) {
376 mbeanServer.removeNotificationListener(on, this);
378 } catch (Exception e) {
379 logger.warn("Unable to unregister {} as listener for {}", this, on, e);