Mechanical code cleanup (config)
[controller.git] / opendaylight / config / config-persister-impl / src / main / java / org / opendaylight / controller / config / persist / impl / ConfigPusherImpl.java
1 /*
2  * Copyright (c) 2015 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.config.persist.impl;
10
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import com.google.common.base.Function;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.collect.Collections2;
15 import java.io.IOException;
16 import java.util.Collection;
17 import java.util.Date;
18 import java.util.HashSet;
19 import java.util.LinkedHashMap;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.SortedSet;
23 import java.util.concurrent.BlockingQueue;
24 import java.util.concurrent.LinkedBlockingQueue;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import javax.annotation.concurrent.Immutable;
29 import javax.management.MBeanServerConnection;
30 import org.opendaylight.controller.config.api.ConflictingVersionException;
31 import org.opendaylight.controller.config.api.ModuleFactoryNotFoundException;
32 import org.opendaylight.controller.config.api.ValidationException;
33 import org.opendaylight.controller.config.facade.xml.ConfigExecution;
34 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
35 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
36 import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
37 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
38 import org.opendaylight.controller.config.facade.xml.util.Util;
39 import org.opendaylight.controller.config.persist.api.ConfigPusher;
40 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
41 import org.opendaylight.controller.config.persist.api.Persister;
42 import org.opendaylight.controller.config.util.capability.Capability;
43 import org.opendaylight.controller.config.util.xml.DocumentedException;
44 import org.opendaylight.controller.config.util.xml.XmlUtil;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.w3c.dom.Element;
49 import org.xml.sax.SAXException;
50
51 @Immutable
52 public class ConfigPusherImpl implements ConfigPusher {
53     private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
54
55     private static final Date NO_REVISION = new Date(0);
56     private static final int QUEUE_SIZE = 100;
57
58     private final long maxWaitForCapabilitiesMillis;
59     private final long conflictingVersionTimeoutMillis;
60     private final BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<>(QUEUE_SIZE);
61
62     private final ConfigSubsystemFacadeFactory facade;
63     private ConfigPersisterNotificationHandler jmxNotificationHandler;
64
65     public ConfigPusherImpl(ConfigSubsystemFacadeFactory facade, long maxWaitForCapabilitiesMillis,
66                         long conflictingVersionTimeoutMillis) {
67         this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
68         this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
69         this.facade = facade;
70     }
71
72     public void process(List<AutoCloseable> autoCloseables, MBeanServerConnection platformMBeanServer,
73             Persister persisterAggregator, boolean propagateExceptions) throws InterruptedException {
74         while(processSingle(autoCloseables, platformMBeanServer, persisterAggregator, propagateExceptions)) {
75         }
76     }
77
78     boolean processSingle(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer,
79             final Persister persisterAggregator, boolean propagateExceptions) throws InterruptedException {
80         final List<? extends ConfigSnapshotHolder> configs = queue.take();
81         try {
82             internalPushConfigs(configs);
83
84             // Do not register multiple notification handlers
85             if(jmxNotificationHandler == null) {
86                 jmxNotificationHandler =
87                         new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator, facade);
88                 synchronized (autoCloseables) {
89                     autoCloseables.add(jmxNotificationHandler);
90                 }
91             }
92
93             LOG.debug("ConfigPusher has pushed configs {}", configs);
94         } catch (Exception e) {
95             // Exceptions are logged to error downstream
96             LOG.debug("Failed to push some of configs: {}", configs, e);
97
98             if(propagateExceptions) {
99                 if(e instanceof RuntimeException) {
100                     throw (RuntimeException)e;
101                 } else {
102                     throw new IllegalStateException(e);
103                 }
104             } else {
105                 return false;
106             }
107         }
108
109         return true;
110     }
111
112     @Override
113     public void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
114         LOG.debug("Requested to push configs {}", configs);
115         this.queue.put(configs);
116     }
117
118     private LinkedHashMap<? extends ConfigSnapshotHolder, Boolean> internalPushConfigs(List<? extends ConfigSnapshotHolder> configs)
119             throws DocumentedException {
120         LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
121         LinkedHashMap<ConfigSnapshotHolder, Boolean> result = new LinkedHashMap<>();
122         // start pushing snapshots
123         for (ConfigSnapshotHolder configSnapshotHolder : configs) {
124             if (configSnapshotHolder != null) {
125                 LOG.info("Pushing configuration snapshot {}", configSnapshotHolder);
126                 boolean pushResult = false;
127                 try {
128                     pushResult = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
129                 } catch (ConfigSnapshotFailureException e) {
130                     LOG.error("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
131                             "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
132                     throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
133                 }  catch (Exception e) {
134                     String msg = String.format("Failed to apply configuration snapshot: %s", configSnapshotHolder);
135                     LOG.error(msg, e);
136                     throw new IllegalStateException(msg, e);
137                 }
138
139                 LOG.info("Successfully pushed configuration snapshot {}", configSnapshotHolder);
140                 result.put(configSnapshotHolder, pushResult);
141             }
142         }
143         LOG.debug("All configuration snapshots have been pushed successfully.");
144         return result;
145     }
146
147     private synchronized boolean pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
148         ConflictingVersionException lastException;
149         Stopwatch stopwatch = Stopwatch.createUnstarted();
150         do {
151             //TODO wait untill all expected modules are in yangStoreService, do we even need to with yangStoreService instead on netconfOperationService?
152             String idForReporting = configSnapshotHolder.toString();
153             SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
154                     "Expected capabilities must not be null - %s, check %s", idForReporting,
155                     configSnapshotHolder.getClass().getName());
156
157             // wait max time for required capabilities to appear
158             waitForCapabilities(expectedCapabilities, idForReporting);
159             try {
160                 if(!stopwatch.isRunning()) {
161                     stopwatch.start();
162                 }
163                 return pushConfig(configSnapshotHolder);
164             } catch (ConflictingVersionException e) {
165                 lastException = e;
166                 LOG.info("Conflicting version detected, will retry after timeout");
167                 sleep();
168             }
169         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
170         throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
171                 lastException);
172     }
173
174     private void waitForCapabilities(Set<String> expectedCapabilities, String idForReporting) {
175         Stopwatch stopwatch = Stopwatch.createStarted();
176         ConfigPusherException lastException;
177         do {
178             try {
179                 final Set<Capability> currentCaps = facade.getCurrentCapabilities();
180                 final Set<String> notFoundCapabilities = computeNotFoundCapabilities(expectedCapabilities, currentCaps);
181                 if (notFoundCapabilities.isEmpty()) {
182                     return;
183                 } else {
184                     LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
185                             "Expected but not found: {}, all expected {}, current {}",
186                             notFoundCapabilities, expectedCapabilities, currentCaps
187                     );
188                     throw new NotEnoughCapabilitiesException(
189                             "Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundCapabilities, notFoundCapabilities);
190                 }
191             } catch (ConfigPusherException e) {
192                 LOG.debug("Not enough capabilities: {}", e.toString());
193                 lastException = e;
194                 sleep();
195             }
196         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
197
198         LOG.error("Unable to push configuration due to missing yang models." +
199                         " Yang models that are missing, but required by the configuration: {}." +
200                         " For each mentioned model check: " +
201                         " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
202                         " 2. the yang file is present in the system" +
203                         " 3. the bundle with that yang file is present in the system and active" +
204                         " 4. the yang parser did not fail while attempting to parse that model",
205                 ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
206         throw new IllegalStateException("Unable to push configuration due to missing yang models." +
207                 " Required yang models that are missing: "
208                 + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
209     }
210
211     private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, Set<Capability> currentCapabilities) {
212         Collection<String> actual = transformCapabilities(currentCapabilities);
213         Set<String> allNotFound = new HashSet<>(expectedCapabilities);
214         allNotFound.removeAll(actual);
215         return allNotFound;
216     }
217
218     static Set<String> transformCapabilities(final Set<Capability> currentCapabilities) {
219         return new HashSet<>(Collections2.transform(currentCapabilities, new Function<Capability, String>() {
220             @Override
221             public String apply(@Nonnull final Capability input) {
222                 return input.getCapabilityUri();
223             }
224         }));
225     }
226
227     static class ConfigPusherException extends Exception {
228
229         public ConfigPusherException(final String message) {
230             super(message);
231         }
232
233         public ConfigPusherException(final String message, final Throwable cause) {
234             super(message, cause);
235         }
236     }
237
238     static class NotEnoughCapabilitiesException extends ConfigPusherException {
239         private static final long serialVersionUID = 1L;
240         private final Set<String> missingCaps;
241
242         NotEnoughCapabilitiesException(String message, Set<String> missingCaps) {
243             super(message);
244             this.missingCaps = missingCaps;
245         }
246
247         public Set<String> getMissingCaps() {
248             return missingCaps;
249         }
250     }
251
252     private static final class ConfigSnapshotFailureException extends ConfigPusherException {
253
254         private final String configIdForReporting;
255
256         public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
257             super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
258             this.configIdForReporting = configIdForReporting;
259         }
260
261         public String getConfigIdForReporting() {
262             return configIdForReporting;
263         }
264     }
265
266     private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, YangStoreService yangStoreService) {
267
268         Collection<String> actual = Collections2.transform(yangStoreService.getModules(), new Function<Module, String>() {
269             @Nullable
270             @Override
271             public String apply(Module input) {
272                 final String withoutRevision = input.getNamespace().toString() + "?module=" + input.getName();
273                 return !input.getRevision().equals(NO_REVISION) ? withoutRevision + "&revision=" + Util.writeDate(input.getRevision()) : withoutRevision;
274             }
275         });
276
277         Set<String> allNotFound = new HashSet<>(expectedCapabilities);
278         allNotFound.removeAll(actual);
279         return allNotFound;
280     }
281
282     private void sleep() {
283         try {
284             Thread.sleep(100);
285         } catch (InterruptedException e) {
286             Thread.currentThread().interrupt();
287             throw new IllegalStateException(e);
288         }
289     }
290
291     private synchronized boolean pushConfig(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException, ConflictingVersionException {
292         Element xmlToBePersisted;
293         try {
294             xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
295         } catch (SAXException | IOException e) {
296             throw new IllegalStateException("Cannot parse " + configSnapshotHolder, e);
297         }
298         LOG.trace("Pushing last configuration to config mapping: {}", configSnapshotHolder);
299
300         Stopwatch stopwatch = Stopwatch.createStarted();
301         final ConfigSubsystemFacade currentFacade = this.facade.createFacade("config-push");
302         try {
303             ConfigExecution configExecution = createConfigExecution(xmlToBePersisted, currentFacade);
304             executeWithMissingModuleFactoryRetries(currentFacade, configExecution);
305         } catch (ValidationException | DocumentedException | ModuleFactoryNotFoundException e) {
306             LOG.trace("Validation for config: {} failed", configSnapshotHolder, e);
307             throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "edit", e);
308         }
309
310         try {
311             currentFacade.commitSilentTransaction();
312         } catch (ValidationException | DocumentedException e) {
313             throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "commit", e);
314         }
315
316         LOG.trace("Last configuration loaded successfully");
317         LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
318
319         return true;
320     }
321
322     private void executeWithMissingModuleFactoryRetries(ConfigSubsystemFacade facade, ConfigExecution configExecution)
323             throws DocumentedException, ValidationException, ModuleFactoryNotFoundException {
324         Stopwatch stopwatch = Stopwatch.createStarted();
325         ModuleFactoryNotFoundException lastException = null;
326         do {
327             try {
328                 facade.executeConfigExecution(configExecution);
329                 return;
330             } catch (ModuleFactoryNotFoundException e) {
331                 LOG.debug("{} - will retry after timeout", e.toString());
332                 lastException = e;
333                 sleep();
334             }
335         } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
336
337         throw lastException;
338     }
339
340     private ConfigExecution createConfigExecution(Element xmlToBePersisted, final ConfigSubsystemFacade currentFacade) throws DocumentedException {
341         final Config configMapping = currentFacade.getConfigMapping();
342         return currentFacade.getConfigExecution(configMapping, xmlToBePersisted);
343     }
344
345 }