package org.opendaylight.controller.netconf.persist.impl;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
+import java.io.Closeable;
+import java.io.IOException;
+import javax.annotation.concurrent.ThreadSafe;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServerConnection;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
-import org.opendaylight.controller.netconf.client.NetconfClient;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXException;
-
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.*;
-import java.io.Closeable;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetSocketAddress;
-import java.util.Collections;
-import java.util.Set;
/**
- * Responsible for listening for notifications from netconf containing latest
+ * Responsible for listening for notifications from netconf (via JMX) containing latest
* committed configuration that should be persisted, and also for loading last
* configuration.
*/
@ThreadSafe
-public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
-
- private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
-
- private final InetSocketAddress address;
+public class ConfigPersisterNotificationHandler implements Closeable {
- private NetconfClient netconfClient;
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
+ private final MBeanServerConnection mBeanServerConnection;
+ private final NotificationListener listener;
- private final Persister persister;
- private final MBeanServerConnection mbeanServer;
- private Long currentSessionId;
- private final ObjectName on = DefaultCommitOperationMXBean.objectName;
-
- public static final long DEFAULT_TIMEOUT = 40000L;
- private final long timeout;
-
- public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
- MBeanServerConnection mbeanServer) {
- this(persister, address, mbeanServer, DEFAULT_TIMEOUT);
+ public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final Persister persisterAggregator) {
+ this(mBeanServerConnection, new ConfigPersisterNotificationListener(persisterAggregator));
}
- public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
- MBeanServerConnection mbeanServer, long timeout) {
- this.persister = persister;
- this.address = address;
- this.mbeanServer = mbeanServer;
- this.timeout = timeout;
+ public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final NotificationListener notificationListener) {
+ this.mBeanServerConnection = mBeanServerConnection;
+ this.listener = notificationListener;
+ registerAsJMXListener(mBeanServerConnection, listener);
}
- public void init() throws InterruptedException {
- Optional<Persister.ConfigSnapshotHolder> maybeConfig = loadLastConfig();
-
- if (maybeConfig.isPresent()) {
- logger.debug("Last config found {}", persister);
-
- registerToNetconf(maybeConfig.get().getCapabilities());
-
- final String configSnapshot = maybeConfig.get().getConfigSnapshot();
- try {
- pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
- } catch (SAXException | IOException e) {
- throw new IllegalStateException("Unable to load last config", e);
- }
-
- } else {
- // this ensures that netconf is initialized, this is first
- // connection
- // this means we can register as listener for commit
- registerToNetconf(Collections.<String>emptySet());
-
- logger.info("No last config provided by backend storage {}", persister);
+ private static void registerAsJMXListener(final MBeanServerConnection mBeanServerConnection, final NotificationListener listener) {
+ LOG.trace("Called registerAsJMXListener");
+ try {
+ mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.OBJECT_NAME, listener, null, null);
+ } catch (InstanceNotFoundException | IOException e) {
+ throw new IllegalStateException("Cannot register as JMX listener to netconf", e);
}
- registerAsJMXListener();
}
- private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
-
- Set<String> currentCapabilities = Sets.newHashSet();
-
- // TODO think about moving capability subset check to netconf client
- // could be utilized by integration tests
-
- long pollingStart = System.currentTimeMillis();
- int delay = 5000;
-
- int attempt = 0;
-
- while (true) {
- attempt++;
-
- try {
- netconfClient = new NetconfClient(this.toString(), address, delay);
- // TODO is this correct ex to catch ?
- } catch (IllegalStateException e) {
- logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
- Thread.sleep(delay);
- continue;
- }
- currentCapabilities = netconfClient.getCapabilities();
-
- if (isSubset(currentCapabilities, expectedCaps)) {
- logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
- currentSessionId = netconfClient.getSessionId();
- logger.info("Session id received from netconf server: {}", currentSessionId);
- return currentSessionId;
- }
-
- if (System.currentTimeMillis() > pollingStart + timeout) {
- break;
- }
-
- logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
-
- try {
- netconfClient.close();
- } catch (IOException e) {
- throw new RuntimeException("Error closing temporary client " + netconfClient);
+ @Override
+ public synchronized void close() {
+ // unregister from JMX
+ final ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME;
+ try {
+ if (mBeanServerConnection.isRegistered(on)) {
+ mBeanServerConnection.removeNotificationListener(on, listener);
}
-
- Thread.sleep(delay);
+ } catch (final Exception e) {
+ LOG.warn("Unable to unregister {} as listener for {}", listener, on, e);
}
-
- throw new RuntimeException("Netconf server did not provide required capabilities " + expectedCaps
- + " in time, provided capabilities " + currentCapabilities);
-
}
+}
- private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
- for (String exCap : expectedCaps) {
- if (currentCapabilities.contains(exCap) == false)
- return false;
- }
- return true;
- }
+class ConfigPersisterNotificationListener implements NotificationListener {
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationListener.class);
- private void registerAsJMXListener() {
- try {
- mbeanServer.addNotificationListener(on, this, null, null);
- } catch (InstanceNotFoundException | IOException e) {
- throw new RuntimeException("Cannot register as JMX listener to netconf", e);
- }
+ private final Persister persisterAggregator;
+
+ ConfigPersisterNotificationListener(final Persister persisterAggregator) {
+ this.persisterAggregator = persisterAggregator;
}
@Override
- public void handleNotification(Notification notification, Object handback) {
- if (notification instanceof NetconfJMXNotification == false)
+ public void handleNotification(final Notification notification, final Object handback) {
+ if (!(notification instanceof NetconfJMXNotification)) {
return;
+ }
// Socket should not be closed at this point
// Activator unregisters this as JMX listener before close is called
- logger.debug("Received notification {}", notification);
+ LOG.trace("Received notification {}", notification);
if (notification instanceof CommitJMXNotification) {
try {
handleAfterCommitNotification((CommitJMXNotification) notification);
- } catch (Exception e) {
- // TODO: notificationBroadcast support logs only DEBUG
- logger.warn("Exception occured during notification handling: ", e);
+ } catch (final Exception e) {
+ // log exceptions from notification Handler here since
+ // notificationBroadcastSupport logs only DEBUG level
+ LOG.warn("Failed to handle notification {}", notification, e);
throw e;
}
- } else
+ } else {
throw new IllegalStateException("Unknown config registry notification type " + notification);
+ }
}
private void handleAfterCommitNotification(final CommitJMXNotification notification) {
try {
- final XmlElement configElement = XmlElement.fromDomElement(notification.getConfigSnapshot());
- persister.persistConfig(new Persister.ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return XmlUtil.toString(configElement.getDomElement());
- }
-
- @Override
- public Set<String> getCapabilities() {
- return notification.getCapabilities();
- }
- });
- logger.debug("Configuration persisted successfully");
- } catch (IOException e) {
+ persisterAggregator.persistConfig(new CapabilityStrippingConfigSnapshotHolder(notification.getConfigSnapshot(),
+ notification.getCapabilities()));
+ LOG.trace("Configuration persisted successfully");
+ } catch (final IOException e) {
throw new RuntimeException("Unable to persist configuration snapshot", e);
}
}
-
- private Optional<Persister.ConfigSnapshotHolder> loadLastConfig() {
- Optional<Persister.ConfigSnapshotHolder> maybeConfigElement;
- try {
- maybeConfigElement = persister.loadLastConfig();
- } catch (IOException e) {
- throw new RuntimeException("Unable to load configuration", e);
- }
- return maybeConfigElement;
- }
-
- private synchronized void pushLastConfig(Element persistedConfig) {
- StringBuilder response = new StringBuilder("editConfig response = {");
-
- Element configElement = persistedConfig;
- NetconfMessage message = createEditConfigMessage(configElement, "/netconfOp/editConfig.xml");
- NetconfMessage responseMessage = netconfClient.sendMessage(message);
-
- XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
- Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
- element = element.getOnlyChildElement();
-
- checkIsOk(element, responseMessage);
- response.append(XmlUtil.toString(responseMessage.getDocument()));
- response.append("}");
- responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"));
-
- element = XmlElement.fromDomDocument(responseMessage.getDocument());
- Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
- element = element.getOnlyChildElement();
-
- checkIsOk(element, responseMessage);
- response.append("commit response = {");
- response.append(XmlUtil.toString(responseMessage.getDocument()));
- response.append("}");
- logger.debug("Last configuration loaded successfully");
- }
-
- private void checkIsOk(XmlElement element, NetconfMessage responseMessage) {
- if (element.getName().equals(XmlNetconfConstants.OK)) {
- return;
- } else {
- if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
- logger.warn("Can not load last configuration, operation failed");
- throw new IllegalStateException("Can not load last configuration, operation failed: "
- + XmlUtil.toString(responseMessage.getDocument()));
- }
- logger.warn("Can not load last configuration. Operation failed.");
- throw new IllegalStateException("Can not load last configuration. Operation failed: "
- + XmlUtil.toString(responseMessage.getDocument()));
- }
- }
-
- private NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
- try (InputStream stream = getClass().getResourceAsStream(editConfigResourcename)) {
- Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
-
- Document doc = XmlUtil.readXmlToDocument(stream);
-
- doc.getDocumentElement();
- XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
- XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
- editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
- for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
- configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
- }
- editConfigElement.appendChild(configWrapper.getDomElement());
- return new NetconfMessage(doc);
- } catch (IOException | SAXException e) {
- throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
- }
- }
-
- private NetconfMessage getNetconfMessageFromResource(String resource) {
- try (InputStream stream = getClass().getResourceAsStream(resource)) {
- Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
- return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
- } catch (SAXException | IOException e) {
- throw new RuntimeException("Unable to parse message from resources " + resource, e);
- }
- }
-
- @Override
- public synchronized void close() {
- // TODO persister is received from constructor, should not be closed
- // here
- try {
- persister.close();
- } catch (Exception e) {
- logger.warn("Unable to close config persister {}", persister, e);
- }
-
- if (netconfClient != null) {
- try {
- netconfClient.close();
- } catch (Exception e) {
- logger.warn("Unable to close connection to netconf {}", netconfClient, e);
- }
- }
-
- // unregister from JMX
- try {
- if (mbeanServer.isRegistered(on)) {
- mbeanServer.removeNotificationListener(on, this);
- }
- } catch (Exception e) {
- logger.warn("Unable to unregister {} as listener for {}", this, on, e);
- }
- }
}