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.*;
31 import java.io.Closeable;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.net.InetSocketAddress;
35 import java.util.Collections;
39 * Responsible for listening for notifications from netconf containing latest
40 * committed configuration that should be persisted, and also for loading last
44 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
46 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
48 private final InetSocketAddress address;
50 private NetconfClient netconfClient;
52 private final Persister persister;
53 private final MBeanServerConnection mbeanServer;
54 private Long currentSessionId;
56 private final ObjectName on = DefaultCommitOperationMXBean.objectName;
58 public static final long DEFAULT_TIMEOUT = 40000L;
59 private final long timeout;
61 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
62 MBeanServerConnection mbeanServer) {
63 this(persister, address, mbeanServer, DEFAULT_TIMEOUT);
66 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
67 MBeanServerConnection mbeanServer, long timeout) {
68 this.persister = persister;
69 this.address = address;
70 this.mbeanServer = mbeanServer;
71 this.timeout = timeout;
74 public void init() throws InterruptedException {
75 Optional<Persister.ConfigSnapshotHolder> maybeConfig = loadLastConfig();
77 if (maybeConfig.isPresent()) {
78 logger.debug("Last config found {}", persister);
80 registerToNetconf(maybeConfig.get().getCapabilities());
82 final String configSnapshot = maybeConfig.get().getConfigSnapshot();
84 pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
85 } catch (SAXException | IOException e) {
86 throw new IllegalStateException("Unable to load last config", e);
90 // this ensures that netconf is initialized, this is first
92 // this means we can register as listener for commit
93 registerToNetconf(Collections.<String>emptySet());
95 logger.info("No last config provided by backend storage {}", persister);
97 registerAsJMXListener();
100 private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
102 Set<String> currentCapabilities = Sets.newHashSet();
104 // TODO think about moving capability subset check to netconf client
105 // could be utilized by integration tests
107 long pollingStart = System.currentTimeMillis();
116 netconfClient = new NetconfClient(this.toString(), address, delay);
117 // TODO is this correct ex to catch ?
118 } catch (IllegalStateException e) {
119 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
123 currentCapabilities = netconfClient.getCapabilities();
125 if (isSubset(currentCapabilities, expectedCaps)) {
126 logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
127 currentSessionId = netconfClient.getSessionId();
128 logger.info("Session id received from netconf server: {}", currentSessionId);
129 return currentSessionId;
132 if (System.currentTimeMillis() > pollingStart + timeout) {
136 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
139 netconfClient.close();
140 } catch (IOException e) {
141 throw new RuntimeException("Error closing temporary client " + netconfClient);
147 throw new RuntimeException("Netconf server did not provide required capabilities " + expectedCaps
148 + " in time, provided capabilities " + currentCapabilities);
152 private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
153 for (String exCap : expectedCaps) {
154 if (currentCapabilities.contains(exCap) == false)
160 private void registerAsJMXListener() {
162 mbeanServer.addNotificationListener(on, this, null, null);
163 } catch (InstanceNotFoundException | IOException e) {
164 throw new RuntimeException("Cannot register as JMX listener to netconf", e);
169 public void handleNotification(Notification notification, Object handback) {
170 if (notification instanceof NetconfJMXNotification == false)
173 // Socket should not be closed at this point
174 // Activator unregisters this as JMX listener before close is called
176 logger.debug("Received notification {}", notification);
177 if (notification instanceof CommitJMXNotification) {
179 handleAfterCommitNotification((CommitJMXNotification) notification);
180 } catch (Exception e) {
181 // TODO: notificationBroadcast support logs only DEBUG
182 logger.warn("Exception occured during notification handling: ", e);
186 throw new IllegalStateException("Unknown config registry notification type " + notification);
189 private void handleAfterCommitNotification(final CommitJMXNotification notification) {
191 final XmlElement configElement = XmlElement.fromDomElement(notification.getConfigSnapshot());
192 persister.persistConfig(new Persister.ConfigSnapshotHolder() {
194 public String getConfigSnapshot() {
195 return XmlUtil.toString(configElement.getDomElement());
199 public Set<String> getCapabilities() {
200 return notification.getCapabilities();
203 logger.debug("Configuration persisted successfully");
204 } catch (IOException e) {
205 throw new RuntimeException("Unable to persist configuration snapshot", e);
209 private Optional<Persister.ConfigSnapshotHolder> loadLastConfig() {
210 Optional<Persister.ConfigSnapshotHolder> maybeConfigElement;
212 maybeConfigElement = persister.loadLastConfig();
213 } catch (IOException e) {
214 throw new RuntimeException("Unable to load configuration", e);
216 return maybeConfigElement;
219 private synchronized void pushLastConfig(Element persistedConfig) {
220 StringBuilder response = new StringBuilder("editConfig response = {");
222 Element configElement = persistedConfig;
223 NetconfMessage message = createEditConfigMessage(configElement, "/netconfOp/editConfig.xml");
224 NetconfMessage responseMessage = netconfClient.sendMessage(message);
226 XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
227 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
228 element = element.getOnlyChildElement();
230 checkIsOk(element, responseMessage);
231 response.append(XmlUtil.toString(responseMessage.getDocument()));
232 response.append("}");
233 responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"));
235 element = XmlElement.fromDomDocument(responseMessage.getDocument());
236 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
237 element = element.getOnlyChildElement();
239 checkIsOk(element, responseMessage);
240 response.append("commit response = {");
241 response.append(XmlUtil.toString(responseMessage.getDocument()));
242 response.append("}");
243 logger.debug("Last configuration loaded successfully");
246 private void checkIsOk(XmlElement element, NetconfMessage responseMessage) {
247 if (element.getName().equals(XmlNetconfConstants.OK)) {
250 if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
251 logger.warn("Can not load last configuration, operation failed");
252 throw new IllegalStateException("Can not load last configuration, operation failed: "
253 + XmlUtil.toString(responseMessage.getDocument()));
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()));
261 private NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
262 try (InputStream stream = getClass().getResourceAsStream(editConfigResourcename)) {
263 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
265 Document doc = XmlUtil.readXmlToDocument(stream);
267 doc.getDocumentElement();
268 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
269 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
270 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
271 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
272 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
274 editConfigElement.appendChild(configWrapper.getDomElement());
275 return new NetconfMessage(doc);
276 } catch (IOException | SAXException e) {
277 throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
281 private NetconfMessage getNetconfMessageFromResource(String resource) {
282 try (InputStream stream = getClass().getResourceAsStream(resource)) {
283 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
284 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
285 } catch (SAXException | IOException e) {
286 throw new RuntimeException("Unable to parse message from resources " + resource, e);
291 public synchronized void close() {
292 // TODO persister is received from constructor, should not be closed
296 } catch (Exception e) {
297 logger.warn("Unable to close config persister {}", persister, e);
300 if (netconfClient != null) {
302 netconfClient.close();
303 } catch (Exception e) {
304 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
308 // unregister from JMX
310 if (mbeanServer.isRegistered(on)) {
311 mbeanServer.removeNotificationListener(on, this);
313 } catch (Exception e) {
314 logger.warn("Unable to unregister {} as listener for {}", this, on, e);