2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
11 import com.google.common.base.Function;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Sets;
15 import java.lang.ref.SoftReference;
16 import java.util.Collections;
17 import java.util.HashSet;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.ThreadFactory;
23 import java.util.concurrent.atomic.AtomicReference;
24 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
25 import org.opendaylight.controller.netconf.api.Capability;
26 import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
27 import org.opendaylight.controller.netconf.notifications.BaseNetconfNotificationListener;
28 import org.opendaylight.controller.netconf.notifications.BaseNotificationPublisherRegistration;
29 import org.opendaylight.controller.netconf.notifications.NetconfNotificationCollector;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChangeBuilder;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.changed.by.parms.ChangedByBuilder;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.changed.by.parms.changed.by.server.or.user.ServerBuilder;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.model.api.Module;
37 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
39 import org.osgi.framework.BundleContext;
40 import org.osgi.framework.ServiceReference;
41 import org.osgi.util.tracker.ServiceTracker;
42 import org.osgi.util.tracker.ServiceTrackerCustomizer;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public class YangStoreService implements YangStoreContext {
48 private static final Logger LOG = LoggerFactory.getLogger(YangStoreService.class);
51 * This is a rather interesting locking model. We need to guard against both the
52 * cache expiring from GC and being invalidated by schema context change. The
53 * context can change while we are doing processing, so we do not want to block
54 * it, so no synchronization can happen on the methods.
56 * So what we are doing is the following:
58 * We synchronize with GC as usual, using a SoftReference.
60 * The atomic reference is used to synchronize with {@link #refresh()}, e.g. when
61 * refresh happens, it will push a SoftReference(null), e.g. simulate the GC. Now
62 * that may happen while the getter is already busy acting on the old schema context,
63 * so it needs to understand that a refresh has happened and retry. To do that, it
64 * attempts a CAS operation -- if it fails, in knows that the SoftReference has
65 * been replaced and thus it needs to retry.
67 * Note that {@link #getYangStoreSnapshot()} will still use synchronize() internally
68 * to stop multiple threads doing the same work.
70 private final AtomicReference<SoftReference<YangStoreSnapshot>> ref =
71 new AtomicReference<>(new SoftReference<YangStoreSnapshot>(null));
73 private final SchemaContextProvider schemaContextProvider;
74 private final BaseNetconfNotificationListener notificationPublisher;
76 private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
78 public Thread newThread(final Runnable r) {
79 return new Thread(r, "config-netconf-connector-capability-notifications");
83 private final Set<CapabilityListener> listeners = Collections.synchronizedSet(new HashSet<CapabilityListener>());
85 public YangStoreService(final SchemaContextProvider schemaContextProvider, final BundleContext context) {
86 this(schemaContextProvider, new NotificationCollectorTracker(context));
89 public YangStoreService(final SchemaContextProvider schemaContextProvider, final BaseNetconfNotificationListener notificationHandler) {
90 this.schemaContextProvider = schemaContextProvider;
91 this.notificationPublisher = notificationHandler;
94 private synchronized YangStoreContext getYangStoreSnapshot() {
95 SoftReference<YangStoreSnapshot> r = ref.get();
96 YangStoreSnapshot ret = r.get();
99 // We need to be compute a new value
100 ret = new YangStoreSnapshot(schemaContextProvider.getSchemaContext());
102 if (!ref.compareAndSet(r, new SoftReference<>(ret))) {
103 LOG.debug("Concurrent refresh detected, recomputing snapshot");
113 public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
114 return getYangStoreSnapshot().getModuleMXBeanEntryMap();
118 public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
119 return getYangStoreSnapshot().getQNamesToIdentitiesToModuleMXBeanEntries();
123 public Set<Module> getModules() {
124 return getYangStoreSnapshot().getModules();
128 public String getModuleSource(final ModuleIdentifier moduleIdentifier) {
129 return getYangStoreSnapshot().getModuleSource(moduleIdentifier);
132 public void refresh() {
133 final YangStoreSnapshot previous = ref.get().get();
134 ref.set(new SoftReference<YangStoreSnapshot>(null));
135 notificationExecutor.submit(new CapabilityChangeNotifier(previous));
138 public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
139 if(ref.get() == null || ref.get().get() == null) {
140 getYangStoreSnapshot();
143 this.listeners.add(listener);
144 listener.onCapabilitiesAdded(NetconfOperationServiceFactoryImpl.setupCapabilities(ref.get().get()));
146 return new AutoCloseable() {
148 public void close() throws Exception {
149 YangStoreService.this.listeners.remove(listener);
154 private static final Function<Module, Capability> MODULE_TO_CAPABILITY = new Function<Module, Capability>() {
156 public Capability apply(final Module module) {
157 return new NetconfOperationServiceFactoryImpl.YangStoreCapability(module, module.getSource());
161 private final class CapabilityChangeNotifier implements Runnable {
163 private final YangStoreSnapshot previous;
165 public CapabilityChangeNotifier(final YangStoreSnapshot previous) {
166 this.previous = previous;
171 final YangStoreContext current = getYangStoreSnapshot();
173 if(current.equals(previous) == false) {
174 final Sets.SetView<Module> removed = Sets.difference(previous.getModules(), current.getModules());
175 final Sets.SetView<Module> added = Sets.difference(current.getModules(), previous.getModules());
177 // Notify notification manager
178 notificationPublisher.onCapabilityChanged(computeDiff(removed, added));
180 // Notify direct capability listener TODO would it not be better if the capability listeners went through notification manager ?
181 for (final CapabilityListener listener : listeners) {
182 listener.onCapabilitiesAdded(Sets.newHashSet(Collections2.transform(added, MODULE_TO_CAPABILITY)));
184 for (final CapabilityListener listener : listeners) {
185 listener.onCapabilitiesRemoved(Sets.newHashSet(Collections2.transform(removed, MODULE_TO_CAPABILITY)));
191 private static final Function<Module, Uri> MODULE_TO_URI = new Function<Module, Uri>() {
193 public Uri apply(final Module input) {
194 final QName qName = QName.cachedReference(QName.create(input.getQNameModule(), input.getName()));
195 return new Uri(qName.toString());
199 static NetconfCapabilityChange computeDiff(final Sets.SetView<Module> removed, final Sets.SetView<Module> added) {
200 final NetconfCapabilityChangeBuilder netconfCapabilityChangeBuilder = new NetconfCapabilityChangeBuilder();
201 netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build()).build());
202 netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2.transform(removed, MODULE_TO_URI)));
203 netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2.transform(added, MODULE_TO_URI)));
204 // TODO modified should be computed ... but why ?
205 netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
206 return netconfCapabilityChangeBuilder.build();
211 * Looks for NetconfNotificationCollector service and publishes base netconf notifications if possible
213 private static class NotificationCollectorTracker implements ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>, BaseNetconfNotificationListener, AutoCloseable {
215 private final BundleContext context;
216 private final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector> listenerTracker;
217 private BaseNotificationPublisherRegistration publisherReg;
219 public NotificationCollectorTracker(final BundleContext context) {
220 this.context = context;
221 listenerTracker = new ServiceTracker<>(context, NetconfNotificationCollector.class, this);
222 listenerTracker.open();
226 public synchronized NetconfNotificationCollector addingService(final ServiceReference<NetconfNotificationCollector> reference) {
227 closePublisherRegistration();
228 publisherReg = context.getService(reference).registerBaseNotificationPublisher();
233 public synchronized void modifiedService(final ServiceReference<NetconfNotificationCollector> reference, final NetconfNotificationCollector service) {
234 closePublisherRegistration();
235 publisherReg = context.getService(reference).registerBaseNotificationPublisher();
239 public synchronized void removedService(final ServiceReference<NetconfNotificationCollector> reference, final NetconfNotificationCollector service) {
240 closePublisherRegistration();
244 private void closePublisherRegistration() {
245 if(publisherReg != null) {
246 publisherReg.close();
251 public synchronized void close() {
252 closePublisherRegistration();
253 listenerTracker.close();
257 public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
258 if(publisherReg == null) {
259 LOG.warn("Omitting notification due to missing notification service: {}", capabilityChange);
263 publisherReg.onCapabilityChanged(capabilityChange);