Fix star import and enable checkstyle rule to prevent it.
[controller.git] / opendaylight / netconf / config-persister-impl / src / main / java / org / opendaylight / controller / netconf / persist / impl / ConfigPersisterNotificationHandler.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.persist.impl;
10
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;
28
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;
40 import java.util.Set;
41
42 /**
43  * Responsible for listening for notifications from netconf containing latest
44  * committed configuration that should be persisted, and also for loading last
45  * configuration.
46  */
47 @ThreadSafe
48 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
49
50     private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
51
52     private final InetSocketAddress address;
53
54     private NetconfClient netconfClient;
55
56     private final Persister persister;
57     private final MBeanServerConnection mbeanServer;
58     private Long currentSessionId;
59
60     private final ObjectName on = DefaultCommitOperationMXBean.objectName;
61
62     public static final long DEFAULT_TIMEOUT = 40000L;
63     private final long timeout;
64
65     public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
66             MBeanServerConnection mbeanServer) {
67         this(persister, address, mbeanServer, DEFAULT_TIMEOUT);
68     }
69
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;
76     }
77
78     public void init() throws InterruptedException {
79         Optional<Persister.ConfigSnapshotHolder> maybeConfig = loadLastConfig();
80
81         if (maybeConfig.isPresent()) {
82             logger.debug("Last config found {}", persister);
83
84             registerToNetconf(maybeConfig.get().getCapabilities());
85
86             final String configSnapshot = maybeConfig.get().getConfigSnapshot();
87             try {
88                 pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
89             } catch (SAXException | IOException e) {
90                 throw new IllegalStateException("Unable to load last config", e);
91             }
92
93         } else {
94             // this ensures that netconf is initialized, this is first
95             // connection
96             // this means we can register as listener for commit
97             registerToNetconf(Collections.<String>emptySet());
98
99             logger.info("No last config provided by backend storage {}", persister);
100         }
101         registerAsJMXListener();
102     }
103
104     private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
105
106         Set<String> currentCapabilities = Sets.newHashSet();
107
108         // TODO think about moving capability subset check to netconf client
109         // could be utilized by integration tests
110
111         long pollingStart = System.currentTimeMillis();
112         int delay = 5000;
113
114         int attempt = 0;
115
116         while (true) {
117             attempt++;
118
119             try {
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);
124                 Thread.sleep(delay);
125                 continue;
126             }
127             currentCapabilities = netconfClient.getCapabilities();
128
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;
134             }
135
136             if (System.currentTimeMillis() > pollingStart + timeout) {
137                 break;
138             }
139
140             logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
141
142             try {
143                 netconfClient.close();
144             } catch (IOException e) {
145                 throw new RuntimeException("Error closing temporary client " + netconfClient);
146             }
147
148             Thread.sleep(delay);
149         }
150
151         throw new RuntimeException("Netconf server did not provide required capabilities " + expectedCaps
152                 + " in time, provided capabilities " + currentCapabilities);
153
154     }
155
156     private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
157         for (String exCap : expectedCaps) {
158             if (currentCapabilities.contains(exCap) == false)
159                 return false;
160         }
161         return true;
162     }
163
164     private void registerAsJMXListener() {
165         try {
166             mbeanServer.addNotificationListener(on, this, null, null);
167         } catch (InstanceNotFoundException | IOException e) {
168             throw new RuntimeException("Cannot register as JMX listener to netconf", e);
169         }
170     }
171
172     @Override
173     public void handleNotification(Notification notification, Object handback) {
174         if (notification instanceof NetconfJMXNotification == false)
175             return;
176
177         // Socket should not be closed at this point
178         // Activator unregisters this as JMX listener before close is called
179
180         logger.debug("Received notification {}", notification);
181         if (notification instanceof CommitJMXNotification) {
182             try {
183                 handleAfterCommitNotification((CommitJMXNotification) notification);
184             } catch (Exception e) {
185                 // TODO: notificationBroadcast support logs only DEBUG
186                 logger.warn("Exception occured during notification handling: ", e);
187                 throw e;
188             }
189         } else
190             throw new IllegalStateException("Unknown config registry notification type " + notification);
191     }
192
193     private void handleAfterCommitNotification(final CommitJMXNotification notification) {
194         try {
195             final XmlElement configElement = XmlElement.fromDomElement(notification.getConfigSnapshot());
196             persister.persistConfig(new Persister.ConfigSnapshotHolder() {
197                 @Override
198                 public String getConfigSnapshot() {
199                     return XmlUtil.toString(configElement.getDomElement());
200                 }
201
202                 @Override
203                 public Set<String> getCapabilities() {
204                     return notification.getCapabilities();
205                 }
206             });
207             logger.debug("Configuration persisted successfully");
208         } catch (IOException e) {
209             throw new RuntimeException("Unable to persist configuration snapshot", e);
210         }
211     }
212
213     private Optional<Persister.ConfigSnapshotHolder> loadLastConfig() {
214         Optional<Persister.ConfigSnapshotHolder> maybeConfigElement;
215         try {
216             maybeConfigElement = persister.loadLastConfig();
217         } catch (IOException e) {
218             throw new RuntimeException("Unable to load configuration", e);
219         }
220         return maybeConfigElement;
221     }
222
223     private synchronized void pushLastConfig(Element persistedConfig) {
224         StringBuilder response = new StringBuilder("editConfig response = {");
225
226         Element configElement = persistedConfig;
227         NetconfMessage message = createEditConfigMessage(configElement, "/netconfOp/editConfig.xml");
228         NetconfMessage responseMessage = netconfClient.sendMessage(message);
229
230         XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
231         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
232         element = element.getOnlyChildElement();
233
234         checkIsOk(element, responseMessage);
235         response.append(XmlUtil.toString(responseMessage.getDocument()));
236         response.append("}");
237         responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"));
238
239         element = XmlElement.fromDomDocument(responseMessage.getDocument());
240         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
241         element = element.getOnlyChildElement();
242
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");
248     }
249
250     private void checkIsOk(XmlElement element, NetconfMessage responseMessage) {
251         if (element.getName().equals(XmlNetconfConstants.OK)) {
252             return;
253         } else {
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()));
258             }
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()));
262         }
263     }
264
265     private NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
266         try (InputStream stream = getClass().getResourceAsStream(editConfigResourcename)) {
267             Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
268
269             Document doc = XmlUtil.readXmlToDocument(stream);
270
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));
277             }
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);
282         }
283     }
284
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);
291         }
292     }
293
294     @Override
295     public synchronized void close() {
296         // TODO persister is received from constructor, should not be closed
297         // here
298         try {
299             persister.close();
300         } catch (Exception e) {
301             logger.warn("Unable to close config persister {}", persister, e);
302         }
303
304         if (netconfClient != null) {
305             try {
306                 netconfClient.close();
307             } catch (Exception e) {
308                 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
309             }
310         }
311
312         // unregister from JMX
313         try {
314             if (mbeanServer.isRegistered(on)) {
315                 mbeanServer.removeNotificationListener(on, this);
316             }
317         } catch (Exception e) {
318             logger.warn("Unable to unregister {} as listener for {}", this, on, e);
319         }
320     }
321 }