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 org.opendaylight.controller.config.persist.api.Persister;
15 import org.opendaylight.controller.netconf.api.NetconfMessage;
16 import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
17 import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
18 import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
19 import org.opendaylight.controller.netconf.client.NetconfClient;
20 import org.opendaylight.controller.netconf.util.xml.XmlElement;
21 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
22 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import org.w3c.dom.Document;
26 import org.w3c.dom.Element;
27 import org.xml.sax.SAXException;
29 import javax.annotation.concurrent.ThreadSafe;
30 import javax.management.InstanceNotFoundException;
31 import javax.management.MBeanServerConnection;
32 import javax.management.Notification;
33 import javax.management.NotificationListener;
34 import javax.management.ObjectName;
35 import java.io.Closeable;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.net.InetSocketAddress;
39 import java.util.Collections;
43 * Responsible for listening for notifications from netconf containing latest
44 * committed configuration that should be persisted, and also for loading last
48 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
50 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
52 private final InetSocketAddress address;
54 private NetconfClient netconfClient;
56 private final Persister persister;
57 private final MBeanServerConnection mbeanServer;
58 private Long currentSessionId;
60 private final ObjectName on = DefaultCommitOperationMXBean.objectName;
62 public static final long DEFAULT_TIMEOUT = 40000L;
63 private final long timeout;
65 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
66 MBeanServerConnection mbeanServer) {
67 this(persister, address, mbeanServer, DEFAULT_TIMEOUT);
70 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
71 MBeanServerConnection mbeanServer, long timeout) {
72 this.persister = persister;
73 this.address = address;
74 this.mbeanServer = mbeanServer;
75 this.timeout = timeout;
78 public void init() throws InterruptedException {
79 Optional<Persister.ConfigSnapshotHolder> maybeConfig = loadLastConfig();
81 if (maybeConfig.isPresent()) {
82 logger.debug("Last config found {}", persister);
84 registerToNetconf(maybeConfig.get().getCapabilities());
86 final String configSnapshot = maybeConfig.get().getConfigSnapshot();
88 pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
89 } catch (SAXException | IOException e) {
90 throw new IllegalStateException("Unable to load last config", e);
94 // this ensures that netconf is initialized, this is first
96 // this means we can register as listener for commit
97 registerToNetconf(Collections.<String>emptySet());
99 logger.info("No last config provided by backend storage {}", persister);
101 registerAsJMXListener();
104 private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
106 Set<String> currentCapabilities = Sets.newHashSet();
108 // TODO think about moving capability subset check to netconf client
109 // could be utilized by integration tests
111 long pollingStart = System.currentTimeMillis();
120 netconfClient = new NetconfClient(this.toString(), address, delay);
121 // TODO is this correct ex to catch ?
122 } catch (IllegalStateException e) {
123 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
127 currentCapabilities = netconfClient.getCapabilities();
129 if (isSubset(currentCapabilities, expectedCaps)) {
130 logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
131 currentSessionId = netconfClient.getSessionId();
132 logger.info("Session id received from netconf server: {}", currentSessionId);
133 return currentSessionId;
136 if (System.currentTimeMillis() > pollingStart + timeout) {
140 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
143 netconfClient.close();
144 } catch (IOException e) {
145 throw new RuntimeException("Error closing temporary client " + netconfClient);
151 throw new RuntimeException("Netconf server did not provide required capabilities " + expectedCaps
152 + " in time, provided capabilities " + currentCapabilities);
156 private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
157 for (String exCap : expectedCaps) {
158 if (currentCapabilities.contains(exCap) == false)
164 private void registerAsJMXListener() {
166 mbeanServer.addNotificationListener(on, this, null, null);
167 } catch (InstanceNotFoundException | IOException e) {
168 throw new RuntimeException("Cannot register as JMX listener to netconf", e);
173 public void handleNotification(Notification notification, Object handback) {
174 if (notification instanceof NetconfJMXNotification == false)
177 // Socket should not be closed at this point
178 // Activator unregisters this as JMX listener before close is called
180 logger.debug("Received notification {}", notification);
181 if (notification instanceof CommitJMXNotification) {
183 handleAfterCommitNotification((CommitJMXNotification) notification);
184 } catch (Exception e) {
185 // TODO: notificationBroadcast support logs only DEBUG
186 logger.warn("Exception occured during notification handling: ", e);
190 throw new IllegalStateException("Unknown config registry notification type " + notification);
193 private void handleAfterCommitNotification(final CommitJMXNotification notification) {
195 final XmlElement configElement = XmlElement.fromDomElement(notification.getConfigSnapshot());
196 persister.persistConfig(new Persister.ConfigSnapshotHolder() {
198 public String getConfigSnapshot() {
199 return XmlUtil.toString(configElement.getDomElement());
203 public Set<String> getCapabilities() {
204 return notification.getCapabilities();
207 logger.debug("Configuration persisted successfully");
208 } catch (IOException e) {
209 throw new RuntimeException("Unable to persist configuration snapshot", e);
213 private Optional<Persister.ConfigSnapshotHolder> loadLastConfig() {
214 Optional<Persister.ConfigSnapshotHolder> maybeConfigElement;
216 maybeConfigElement = persister.loadLastConfig();
217 } catch (IOException e) {
218 throw new RuntimeException("Unable to load configuration", e);
220 return maybeConfigElement;
223 private synchronized void pushLastConfig(Element persistedConfig) {
224 StringBuilder response = new StringBuilder("editConfig response = {");
226 Element configElement = persistedConfig;
227 NetconfMessage message = createEditConfigMessage(configElement, "/netconfOp/editConfig.xml");
228 NetconfMessage responseMessage = netconfClient.sendMessage(message);
230 XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
231 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
232 element = element.getOnlyChildElement();
234 checkIsOk(element, responseMessage);
235 response.append(XmlUtil.toString(responseMessage.getDocument()));
236 response.append("}");
237 responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"));
239 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("commit response = {");
245 response.append(XmlUtil.toString(responseMessage.getDocument()));
246 response.append("}");
247 logger.debug("Last configuration loaded successfully");
250 private void checkIsOk(XmlElement element, NetconfMessage responseMessage) {
251 if (element.getName().equals(XmlNetconfConstants.OK)) {
254 if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
255 logger.warn("Can not load last configuration, operation failed");
256 throw new IllegalStateException("Can not load last configuration, operation failed: "
257 + XmlUtil.toString(responseMessage.getDocument()));
259 logger.warn("Can not load last configuration. Operation failed.");
260 throw new IllegalStateException("Can not load last configuration. Operation failed: "
261 + XmlUtil.toString(responseMessage.getDocument()));
265 private NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
266 try (InputStream stream = getClass().getResourceAsStream(editConfigResourcename)) {
267 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
269 Document doc = XmlUtil.readXmlToDocument(stream);
271 doc.getDocumentElement();
272 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
273 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
274 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
275 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
276 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
278 editConfigElement.appendChild(configWrapper.getDomElement());
279 return new NetconfMessage(doc);
280 } catch (IOException | SAXException e) {
281 throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
285 private NetconfMessage getNetconfMessageFromResource(String resource) {
286 try (InputStream stream = getClass().getResourceAsStream(resource)) {
287 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
288 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
289 } catch (SAXException | IOException e) {
290 throw new RuntimeException("Unable to parse message from resources " + resource, e);
295 public synchronized void close() {
296 // TODO persister is received from constructor, should not be closed
300 } catch (Exception e) {
301 logger.warn("Unable to close config persister {}", persister, e);
304 if (netconfClient != null) {
306 netconfClient.close();
307 } catch (Exception e) {
308 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
312 // unregister from JMX
314 if (mbeanServer.isRegistered(on)) {
315 mbeanServer.removeNotificationListener(on, this);
317 } catch (Exception e) {
318 logger.warn("Unable to unregister {} as listener for {}", this, on, e);