CDS: Add stress test RPC to the cars model
[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.Capability;
37 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
38 import org.opendaylight.controller.netconf.api.NetconfMessage;
39 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
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 = null;
102                 try {
103                     editAndCommitResponseWithRetries = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
104                 } catch (ConfigSnapshotFailureException e) {
105                     LOG.warn("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
106                             "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
107                     throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
108                 }
109                 LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
110                 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
111             }
112         }
113         LOG.debug("All configuration snapshots have been pushed successfully.");
114         return result;
115     }
116
117     /**
118      * First calls {@link #getOperationServiceWithRetries(java.util.Set, String)} in order to wait until
119      * expected capabilities are present, then tries to push configuration. If {@link ConflictingVersionException}
120      * is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
121      * {@link NetconfOperationService} after each use.
122      */
123     private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
124         ConflictingVersionException lastException;
125         Stopwatch stopwatch = Stopwatch.createUnstarted();
126         do {
127             String idForReporting = configSnapshotHolder.toString();
128             SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
129                     "Expected capabilities must not be null - %s, check %s", idForReporting,
130                     configSnapshotHolder.getClass().getName());
131             try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
132                 if(!stopwatch.isRunning()) {
133                     stopwatch.start();
134                 }
135                 return pushConfig(configSnapshotHolder, operationService);
136             } catch (ConflictingVersionException e) {
137                 lastException = e;
138                 LOG.info("Conflicting version detected, will retry after timeout");
139                 sleep();
140             }
141         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
142         throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
143                 lastException);
144     }
145
146     private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities, String idForReporting) {
147         Stopwatch stopwatch = Stopwatch.createStarted();
148         ConfigPusherException lastException;
149         do {
150             try {
151                 return getOperationService(expectedCapabilities, idForReporting);
152             } catch (ConfigPusherException e) {
153                 LOG.debug("Not enough capabilities: {}", e.toString());
154                 lastException = e;
155                 sleep();
156             }
157         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
158
159         if(lastException instanceof NotEnoughCapabilitiesException) {
160             LOG.error("Unable to push configuration due to missing yang models." +
161                             " Yang models that are missing, but required by the configuration: {}." +
162                             " For each mentioned model check: " +
163                             " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
164                             " 2. the yang file is present in the system" +
165                             " 3. the bundle with that yang file is present in the system and active" +
166                             " 4. the yang parser did not fail while attempting to parse that model",
167                     ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
168             throw new IllegalStateException("Unable to push configuration due to missing yang models." +
169                     " Required yang models that are missing: "
170                     + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
171         } else {
172             final String msg = "Unable to push configuration due to missing netconf service";
173             LOG.error(msg, lastException);
174             throw new IllegalStateException(msg, lastException);
175         }
176     }
177
178     private static class ConfigPusherException extends Exception {
179
180         public ConfigPusherException(final String message) {
181             super(message);
182         }
183
184         public ConfigPusherException(final String message, final Throwable cause) {
185             super(message, cause);
186         }
187     }
188
189     private static class NotEnoughCapabilitiesException extends ConfigPusherException {
190         private static final long serialVersionUID = 1L;
191         private Set<String> missingCaps;
192
193         private NotEnoughCapabilitiesException(String message, Set<String> missingCaps) {
194             super(message);
195             this.missingCaps = missingCaps;
196         }
197
198         public Set<String> getMissingCaps() {
199             return missingCaps;
200         }
201     }
202
203     private static final class NetconfServiceNotAvailableException extends ConfigPusherException {
204
205         public NetconfServiceNotAvailableException(final String s, final RuntimeException e) {
206             super(s, e);
207         }
208     }
209
210     private static final class ConfigSnapshotFailureException extends ConfigPusherException {
211
212         private final String configIdForReporting;
213
214         public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
215             super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
216             this.configIdForReporting = configIdForReporting;
217         }
218
219         public String getConfigIdForReporting() {
220             return configIdForReporting;
221         }
222     }
223
224     /**
225      * Get NetconfOperationService iif all required capabilities are present.
226      *
227      * @param expectedCapabilities that must be provided by configNetconfConnector
228      * @param idForReporting
229      * @return service if capabilities are present, otherwise absent value
230      */
231     private NetconfOperationService getOperationService(Set<String> expectedCapabilities, String idForReporting) throws ConfigPusherException {
232         NetconfOperationService serviceCandidate;
233         try {
234             serviceCandidate = configNetconfConnector.createService(idForReporting);
235         } catch(RuntimeException e) {
236             throw new NetconfServiceNotAvailableException("Netconf service not stable for config pusher." +
237                     " Cannot push any configuration", e);
238         }
239         Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, configNetconfConnector);
240         if (notFoundDiff.isEmpty()) {
241             return serviceCandidate;
242         } else {
243             serviceCandidate.close();
244             LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
245                     "Expected but not found: {}, all expected {}, current {}",
246                      notFoundDiff, expectedCapabilities, configNetconfConnector.getCapabilities()
247             );
248             throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff, notFoundDiff);
249         }
250     }
251
252     private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationServiceFactory serviceCandidate) {
253         Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
254             @Override
255             public String apply(@Nonnull final Capability input) {
256                 return input.getCapabilityUri();
257             }
258         });
259         Set<String> allNotFound = new HashSet<>(expectedCapabilities);
260         allNotFound.removeAll(actual);
261         return allNotFound;
262     }
263
264     private void sleep() {
265         try {
266             Thread.sleep(100);
267         } catch (InterruptedException e) {
268             Thread.currentThread().interrupt();
269             throw new IllegalStateException(e);
270         }
271     }
272
273     /**
274      * Sends two RPCs to the netconf server: edit-config and commit.
275      *
276      * @param configSnapshotHolder
277      * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
278      * @throws java.lang.RuntimeException  if edit-config or commit fails otherwise
279      */
280     private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
281             throws ConflictingVersionException, ConfigSnapshotFailureException {
282
283         Element xmlToBePersisted;
284         try {
285             xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
286         } catch (SAXException | IOException e) {
287             throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
288         }
289         LOG.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
290         Stopwatch stopwatch = Stopwatch.createStarted();
291         NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
292
293         Document editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, operationService,
294                 "edit-config", configSnapshotHolder.toString());
295
296         Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService,
297                 "commit", configSnapshotHolder.toString());
298
299         if (LOG.isTraceEnabled()) {
300             StringBuilder response = new StringBuilder("editConfig response = {");
301             response.append(XmlUtil.toString(editResponseMessage));
302             response.append("}");
303             response.append("commit response = {");
304             response.append(XmlUtil.toString(commitResponseMessage));
305             response.append("}");
306             LOG.trace("Last configuration loaded successfully");
307             LOG.trace("Detailed message {}", response);
308             LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
309         }
310         return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
311     }
312
313     private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) {
314         TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
315         Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
316         if (netconfOperations.isEmpty()) {
317             throw new IllegalStateException("Possible code error: no config operations");
318         }
319         for (NetconfOperation netconfOperation : netconfOperations) {
320             HandlingPriority handlingPriority = null;
321             try {
322                 handlingPriority = netconfOperation.canHandle(request.getDocument());
323             } catch (NetconfDocumentedException e) {
324                 throw new IllegalStateException("Possible code error: canHandle threw exception", e);
325             }
326             allOperations.put(handlingPriority, netconfOperation);
327         }
328         Entry<HandlingPriority, NetconfOperation> highestEntry = allOperations.lastEntry();
329         if (highestEntry.getKey().isCannotHandle()) {
330             throw new IllegalStateException("Possible code error: operation with highest priority is CANNOT_HANDLE");
331         }
332         return highestEntry.getValue();
333     }
334
335     private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
336                                                      String operationNameForReporting, String configIdForReporting)
337             throws ConflictingVersionException, ConfigSnapshotFailureException {
338
339         NetconfOperation operation = findOperation(request, operationService);
340         Document response;
341         try {
342             response = operation.handle(request.getDocument(), NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
343             return NetconfUtil.checkIsMessageOk(response);
344         } catch (NetconfDocumentedException e) {
345             if (e.getCause() instanceof ConflictingVersionException) {
346                 throw (ConflictingVersionException) e.getCause();
347             }
348             throw new ConfigSnapshotFailureException(configIdForReporting, operationNameForReporting, e);
349         }
350     }
351
352     // load editConfig.xml template, populate /rpc/edit-config/config with parameter
353     private static NetconfMessage createEditConfigMessage(Element dataElement) {
354         String editConfigResourcePath = "/netconfOp/editConfig.xml";
355         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
356             checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
357
358             Document doc = XmlUtil.readXmlToDocument(stream);
359
360             XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
361             XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
362             editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
363             for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
364                 boolean deep = true;
365                 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
366             }
367             editConfigElement.appendChild(configWrapper.getDomElement());
368             return new NetconfMessage(doc);
369         } catch (IOException | SAXException | NetconfDocumentedException e) {
370             // error reading the xml file bundled into the jar
371             throw new IllegalStateException("Error while opening local resource " + editConfigResourcePath, e);
372         }
373     }
374
375     private static NetconfMessage getCommitMessage() {
376         String resource = "/netconfOp/commit.xml";
377         try (InputStream stream = ConfigPusherImpl.class.getResourceAsStream(resource)) {
378             checkNotNull(stream, "Unable to load resource " + resource);
379             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
380         } catch (SAXException | IOException e) {
381             // error reading the xml file bundled into the jar
382             throw new IllegalStateException("Error while opening local resource " + resource, e);
383         }
384     }
385
386     static class EditAndCommitResponse {
387         private final Document editResponse, commitResponse;
388
389         EditAndCommitResponse(Document editResponse, Document commitResponse) {
390             this.editResponse = editResponse;
391             this.commitResponse = commitResponse;
392         }
393
394         public Document getEditResponse() {
395             return editResponse;
396         }
397
398         public Document getCommitResponse() {
399             return commitResponse;
400         }
401
402         @Override
403         public String toString() {
404             return "EditAndCommitResponse{" +
405                     "editResponse=" + editResponse +
406                     ", commitResponse=" + commitResponse +
407                     '}';
408         }
409     }
410 }