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