Merge "BUG-2470: add trace of failed modification"
[controller.git] / opendaylight / netconf / config-persister-impl / src / main / java / org / opendaylight / controller / netconf / persist / impl / ConfigPusherImpl.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 static com.google.common.base.Preconditions.checkNotNull;
12
13 import com.google.common.base.Function;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.collect.Collections2;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.Collection;
19 import java.util.HashSet;
20 import java.util.LinkedHashMap;
21 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.Set;
24 import java.util.SortedSet;
25 import java.util.TreeMap;
26 import java.util.concurrent.BlockingQueue;
27 import java.util.concurrent.LinkedBlockingQueue;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.Nonnull;
30 import javax.annotation.concurrent.Immutable;
31 import javax.management.MBeanServerConnection;
32 import org.opendaylight.controller.config.api.ConflictingVersionException;
33 import org.opendaylight.controller.config.persist.api.ConfigPusher;
34 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
35 import org.opendaylight.controller.config.persist.api.Persister;
36 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
37 import org.opendaylight.controller.netconf.api.NetconfMessage;
38 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
39 import org.opendaylight.controller.netconf.mapping.api.Capability;
40 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
41 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
42 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
43 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
44 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
45 import org.opendaylight.controller.netconf.util.NetconfUtil;
46 import org.opendaylight.controller.netconf.util.xml.XmlElement;
47 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Document;
51 import org.w3c.dom.Element;
52 import org.xml.sax.SAXException;
53
54 @Immutable
55 public class ConfigPusherImpl implements ConfigPusher {
56     private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
57
58     private final long maxWaitForCapabilitiesMillis;
59     private final long conflictingVersionTimeoutMillis;
60     private final NetconfOperationServiceFactory configNetconfConnector;
61     private static final int QUEUE_SIZE = 100;
62     private BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<List<? extends ConfigSnapshotHolder>>(QUEUE_SIZE);
63
64     public ConfigPusherImpl(NetconfOperationServiceFactory configNetconfConnector, long maxWaitForCapabilitiesMillis,
65                         long conflictingVersionTimeoutMillis) {
66         this.configNetconfConnector = configNetconfConnector;
67         this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
68         this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
69     }
70
71     public void process(List<AutoCloseable> autoCloseables, MBeanServerConnection platformMBeanServer, Persister persisterAggregator) throws InterruptedException {
72         List<? extends ConfigSnapshotHolder> configs;
73         while(true) {
74             configs = queue.take();
75             try {
76                 internalPushConfigs(configs);
77                 ConfigPersisterNotificationHandler jmxNotificationHandler = new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator);
78                 synchronized (autoCloseables) {
79                     autoCloseables.add(jmxNotificationHandler);
80                 }
81
82                 LOG.debug("ConfigPusher has pushed configs {}", configs);
83             } catch (NetconfDocumentedException e) {
84                 LOG.error("Error pushing configs {}",configs);
85                 throw new IllegalStateException(e);
86             }
87         }
88     }
89
90     public void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
91         LOG.debug("Requested to push configs {}", configs);
92         this.queue.put(configs);
93     }
94
95     private LinkedHashMap<? extends ConfigSnapshotHolder, EditAndCommitResponse> internalPushConfigs(List<? extends ConfigSnapshotHolder> configs) throws NetconfDocumentedException {
96         LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
97         LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> result = new LinkedHashMap<>();
98         // start pushing snapshots:
99         for (ConfigSnapshotHolder configSnapshotHolder : configs) {
100             if(configSnapshotHolder != null) {
101                 EditAndCommitResponse editAndCommitResponseWithRetries = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
102                 LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
103                 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
104             }
105         }
106         LOG.debug("All configuration snapshots have been pushed successfully.");
107         return result;
108     }
109
110     /**
111      * First calls {@link #getOperationServiceWithRetries(java.util.Set, String)} in order to wait until
112      * expected capabilities are present, then tries to push configuration. If {@link ConflictingVersionException}
113      * is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
114      * {@link NetconfOperationService} after each use.
115      */
116     private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws NetconfDocumentedException {
117         ConflictingVersionException lastException;
118         Stopwatch stopwatch = new Stopwatch().start();
119         do {
120             String idForReporting = configSnapshotHolder.toString();
121             SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
122                     "Expected capabilities must not be null - %s, check %s", idForReporting,
123                     configSnapshotHolder.getClass().getName());
124             try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
125                 return pushConfig(configSnapshotHolder, operationService);
126             } catch (ConflictingVersionException e) {
127                 lastException = e;
128                 LOG.debug("Conflicting version detected, will retry after timeout");
129                 sleep();
130             }
131         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
132         throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
133                 lastException);
134     }
135
136     private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities, String idForReporting) {
137         Stopwatch stopwatch = new Stopwatch().start();
138         NotEnoughCapabilitiesException lastException;
139         do {
140             try {
141                 return getOperationService(expectedCapabilities, idForReporting);
142             } catch (NotEnoughCapabilitiesException e) {
143                 LOG.debug("Not enough capabilities: {}", e.toString());
144                 lastException = e;
145                 sleep();
146             }
147         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
148         throw new IllegalStateException("Max wait for capabilities reached." + lastException.getMessage(), lastException);
149     }
150
151     private static class NotEnoughCapabilitiesException extends Exception {
152         private static final long serialVersionUID = 1L;
153
154         private NotEnoughCapabilitiesException(String message, Throwable cause) {
155             super(message, cause);
156         }
157
158         private NotEnoughCapabilitiesException(String message) {
159             super(message);
160         }
161     }
162
163     /**
164      * Get NetconfOperationService iif all required capabilities are present.
165      *
166      * @param expectedCapabilities that must be provided by configNetconfConnector
167      * @param idForReporting
168      * @return service if capabilities are present, otherwise absent value
169      */
170     private NetconfOperationService getOperationService(Set<String> expectedCapabilities, String idForReporting) throws NotEnoughCapabilitiesException {
171         NetconfOperationService serviceCandidate;
172         try {
173             serviceCandidate = configNetconfConnector.createService(idForReporting);
174         } catch(RuntimeException e) {
175             throw new NotEnoughCapabilitiesException("Netconf service not stable for " + idForReporting, e);
176         }
177         Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, serviceCandidate);
178         if (notFoundDiff.isEmpty()) {
179             return serviceCandidate;
180         } else {
181             serviceCandidate.close();
182             LOG.trace("Netconf server did not provide required capabilities for {} ", idForReporting,
183                     "Expected but not found: {}, all expected {}, current {}",
184                      notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities()
185             );
186             throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff);
187         }
188     }
189
190     private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationService serviceCandidate) {
191         Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
192             @Override
193             public String apply(@Nonnull final Capability input) {
194                 return input.getCapabilityUri();
195             }
196         });
197         Set<String> allNotFound = new HashSet<>(expectedCapabilities);
198         allNotFound.removeAll(actual);
199         return allNotFound;
200     }
201
202
203
204     private void sleep() {
205         try {
206             Thread.sleep(100);
207         } catch (InterruptedException e) {
208             Thread.currentThread().interrupt();
209             throw new IllegalStateException(e);
210         }
211     }
212
213     /**
214      * Sends two RPCs to the netconf server: edit-config and commit.
215      *
216      * @param configSnapshotHolder
217      * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
218      * @throws java.lang.RuntimeException  if edit-config or commit fails otherwise
219      */
220     private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
221             throws ConflictingVersionException, NetconfDocumentedException {
222
223         Element xmlToBePersisted;
224         try {
225             xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
226         } catch (SAXException | IOException e) {
227             throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
228         }
229         LOG.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
230         Stopwatch stopwatch = new Stopwatch().start();
231         NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
232
233         Document editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, operationService,
234                 "edit-config", configSnapshotHolder.toString());
235
236         Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService,
237                 "commit", configSnapshotHolder.toString());
238
239         if (LOG.isTraceEnabled()) {
240             StringBuilder response = new StringBuilder("editConfig response = {");
241             response.append(XmlUtil.toString(editResponseMessage));
242             response.append("}");
243             response.append("commit response = {");
244             response.append(XmlUtil.toString(commitResponseMessage));
245             response.append("}");
246             LOG.trace("Last configuration loaded successfully");
247             LOG.trace("Detailed message {}", response);
248             LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
249         }
250         return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
251     }
252
253     private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) throws NetconfDocumentedException {
254         TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
255         Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
256         if (netconfOperations.isEmpty()) {
257             throw new IllegalStateException("Possible code error: no config operations");
258         }
259         for (NetconfOperation netconfOperation : netconfOperations) {
260             HandlingPriority handlingPriority = netconfOperation.canHandle(request.getDocument());
261             allOperations.put(handlingPriority, netconfOperation);
262         }
263         Entry<HandlingPriority, NetconfOperation> highestEntry = allOperations.lastEntry();
264         if (highestEntry.getKey().isCannotHandle()) {
265             throw new IllegalStateException("Possible code error: operation with highest priority is CANNOT_HANDLE");
266         }
267         return highestEntry.getValue();
268     }
269
270     private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
271                                                      String operationNameForReporting, String configIdForReporting)
272             throws ConflictingVersionException, NetconfDocumentedException {
273
274         NetconfOperation operation = findOperation(request, operationService);
275         Document response;
276         try {
277             response = operation.handle(request.getDocument(), NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
278         } catch (NetconfDocumentedException | RuntimeException e) {
279             if (e instanceof NetconfDocumentedException && e.getCause() instanceof ConflictingVersionException) {
280                 throw (ConflictingVersionException) e.getCause();
281             }
282             throw new IllegalStateException("Failed to send " + operationNameForReporting +
283                     " for configuration " + configIdForReporting, e);
284         }
285         return NetconfUtil.checkIsMessageOk(response);
286     }
287
288     // load editConfig.xml template, populate /rpc/edit-config/config with parameter
289     private static NetconfMessage createEditConfigMessage(Element dataElement) throws NetconfDocumentedException {
290         String editConfigResourcePath = "/netconfOp/editConfig.xml";
291         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
292             checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
293
294             Document doc = XmlUtil.readXmlToDocument(stream);
295
296             XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
297             XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
298             editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
299             for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
300                 boolean deep = true;
301                 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
302             }
303             editConfigElement.appendChild(configWrapper.getDomElement());
304             return new NetconfMessage(doc);
305         } catch (IOException | SAXException e) {
306             // error reading the xml file bundled into the jar
307             throw new IllegalStateException("Error while opening local resource " + editConfigResourcePath, e);
308         }
309     }
310
311     private static NetconfMessage getCommitMessage() {
312         String resource = "/netconfOp/commit.xml";
313         try (InputStream stream = ConfigPusherImpl.class.getResourceAsStream(resource)) {
314             checkNotNull(stream, "Unable to load resource " + resource);
315             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
316         } catch (SAXException | IOException e) {
317             // error reading the xml file bundled into the jar
318             throw new IllegalStateException("Error while opening local resource " + resource, e);
319         }
320     }
321
322     static class EditAndCommitResponse {
323         private final Document editResponse, commitResponse;
324
325         EditAndCommitResponse(Document editResponse, Document commitResponse) {
326             this.editResponse = editResponse;
327             this.commitResponse = commitResponse;
328         }
329
330         public Document getEditResponse() {
331             return editResponse;
332         }
333
334         public Document getCommitResponse() {
335             return commitResponse;
336         }
337
338         @Override
339         public String toString() {
340             return "EditAndCommitResponse{" +
341                     "editResponse=" + editResponse +
342                     ", commitResponse=" + commitResponse +
343                     '}';
344         }
345     }
346 }