Merge "Bug 2731: Discard changes only when transaction exist."
[controller.git] / opendaylight / netconf / config-persister-impl / src / main / java / org / opendaylight / controller / netconf / persist / impl / osgi / ConfigPersisterActivator.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.osgi;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import java.lang.management.ManagementFactory;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.atomic.AtomicBoolean;
17 import javax.management.MBeanServer;
18 import org.opendaylight.controller.config.persist.api.ConfigPusher;
19 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
20 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
21 import org.opendaylight.controller.netconf.persist.impl.ConfigPusherImpl;
22 import org.opendaylight.controller.netconf.persist.impl.PersisterAggregator;
23 import org.opendaylight.controller.netconf.util.CloseableUtil;
24 import org.osgi.framework.BundleActivator;
25 import org.osgi.framework.BundleContext;
26 import org.osgi.framework.Constants;
27 import org.osgi.framework.Filter;
28 import org.osgi.framework.InvalidSyntaxException;
29 import org.osgi.framework.ServiceReference;
30 import org.osgi.framework.ServiceRegistration;
31 import org.osgi.util.tracker.ServiceTracker;
32 import org.osgi.util.tracker.ServiceTrackerCustomizer;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 public class ConfigPersisterActivator implements BundleActivator {
37
38     private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterActivator.class);
39     private static final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
40
41     public static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY = "maxWaitForCapabilitiesMillis";
42     private static final long MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(2);
43     public static final String CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY = "conflictingVersionTimeoutMillis";
44     private static final long CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(1);
45
46     public static final String NETCONF_CONFIG_PERSISTER = "netconf.config.persister";
47
48     public static final String STORAGE_ADAPTER_CLASS_PROP_SUFFIX = "storageAdapterClass";
49
50     private List<AutoCloseable> autoCloseables;
51     private volatile BundleContext context;
52
53     ServiceRegistration<?> registration;
54
55     @Override
56     public void start(final BundleContext context) throws Exception {
57         LOG.debug("ConfigPersister starting");
58         this.context = context;
59
60         autoCloseables = new ArrayList<>();
61         PropertiesProviderBaseImpl propertiesProvider = new PropertiesProviderBaseImpl(context);
62
63         final PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(propertiesProvider);
64         autoCloseables.add(persisterAggregator);
65         long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider);
66         List<ConfigSnapshotHolder> configs = persisterAggregator.loadLastConfigs();
67         long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider);
68         LOG.debug("Following configs will be pushed: {}", configs);
69
70         InnerCustomizer innerCustomizer = new InnerCustomizer(configs, maxWaitForCapabilitiesMillis,
71                 conflictingVersionTimeoutMillis, persisterAggregator);
72         OuterCustomizer outerCustomizer = new OuterCustomizer(context, innerCustomizer);
73         new ServiceTracker<>(context, NetconfOperationServiceFactory.class, outerCustomizer).open();
74     }
75
76     private long getConflictingVersionTimeoutMillis(PropertiesProviderBaseImpl propertiesProvider) {
77         String timeoutProperty = propertiesProvider.getProperty(CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY);
78         return timeoutProperty == null ? CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
79     }
80
81     private long getMaxWaitForCapabilitiesMillis(PropertiesProviderBaseImpl propertiesProvider) {
82         String timeoutProperty = propertiesProvider.getProperty(MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY);
83         return timeoutProperty == null ? MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
84     }
85
86     @Override
87     public void stop(BundleContext context) throws Exception {
88         synchronized(autoCloseables) {
89             CloseableUtil.closeAll(autoCloseables);
90             if (registration != null) {
91                 registration.unregister();
92             }
93             this.context = null;
94         }
95     }
96
97
98     @VisibleForTesting
99     public static String getFilterString() {
100         return "(&" +
101                 "(" + Constants.OBJECTCLASS + "=" + NetconfOperationServiceFactory.class.getName() + ")" +
102                 "(name" + "=" + "config-netconf-connector" + ")" +
103                 ")";
104     }
105
106     class OuterCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> {
107         private final BundleContext context;
108         private final InnerCustomizer innerCustomizer;
109
110         OuterCustomizer(BundleContext context, InnerCustomizer innerCustomizer) {
111             this.context = context;
112             this.innerCustomizer = innerCustomizer;
113         }
114
115         @Override
116         public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
117             LOG.trace("Got OuterCustomizer.addingService {}", reference);
118             // JMX was registered, track config-netconf-connector
119             Filter filter;
120             try {
121                 filter = context.createFilter(getFilterString());
122             } catch (InvalidSyntaxException e) {
123                 throw new IllegalStateException(e);
124             }
125             new ServiceTracker<>(context, filter, innerCustomizer).open();
126             return null;
127         }
128
129         @Override
130         public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
131
132         }
133
134         @Override
135         public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
136
137         }
138     }
139
140     class InnerCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> {
141         private final List<ConfigSnapshotHolder> configs;
142         private final PersisterAggregator persisterAggregator;
143         private final long maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis;
144         // This inner customizer has its filter to find the right operation service, but it gets triggered after any
145         // operation service appears. This means that it could start pushing thread up to N times (N = number of operation services spawned in OSGi)
146         private final AtomicBoolean alreadyStarted = new AtomicBoolean(false);
147
148         InnerCustomizer(List<ConfigSnapshotHolder> configs, long maxWaitForCapabilitiesMillis, long conflictingVersionTimeoutMillis,
149                         PersisterAggregator persisterAggregator) {
150             this.configs = configs;
151             this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
152             this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
153             this.persisterAggregator = persisterAggregator;
154         }
155
156         @Override
157         public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
158             if(alreadyStarted.compareAndSet(false, true) == false) {
159                 //Prevents multiple calls to this method spawning multiple pushing threads
160                 return reference.getBundle().getBundleContext().getService(reference);
161             }
162             LOG.trace("Got InnerCustomizer.addingService {}", reference);
163             NetconfOperationServiceFactory service = reference.getBundle().getBundleContext().getService(reference);
164
165             LOG.debug("Creating new job queue");
166
167             final ConfigPusherImpl configPusher = new ConfigPusherImpl(service, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
168             LOG.debug("Configuration Persister got {}", service);
169             LOG.debug("Context was {}", context);
170             LOG.debug("Registration was {}", registration);
171
172             final Thread pushingThread = new Thread(new Runnable() {
173                 @Override
174                 public void run() {
175                     try {
176                         if(configs != null && !configs.isEmpty()) {
177                             configPusher.pushConfigs(configs);
178                         }
179                         if(context != null) {
180                             registration = context.registerService(ConfigPusher.class.getName(), configPusher, null);
181                             configPusher.process(autoCloseables, platformMBeanServer, persisterAggregator);
182                         } else {
183                             LOG.warn("Unable to process configs as BundleContext is null");
184                         }
185                     } catch (InterruptedException e) {
186                         LOG.info("ConfigPusher thread stopped",e);
187                     }
188                     LOG.info("Configuration Persister initialization completed.");
189                 }
190             }, "config-pusher");
191             synchronized (autoCloseables) {
192                 autoCloseables.add(new AutoCloseable() {
193                     @Override
194                     public void close() {
195                         pushingThread.interrupt();
196                     }
197                 });
198             }
199             pushingThread.start();
200             return service;
201         }
202
203         @Override
204         public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
205             LOG.trace("Got InnerCustomizer.modifiedService {}", reference);
206         }
207
208         @Override
209         public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
210             LOG.trace("Got InnerCustomizer.removedService {}", reference);
211         }
212
213     }
214 }
215