3149b0877bc6df09afe425eaf6e6d5dbd45af193
[controller.git] / opendaylight / config / config-manager-facade-xml / src / main / java / org / opendaylight / controller / config / facade / xml / osgi / YangStoreService.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.facade.xml.osgi;
10
11 import com.google.common.base.Function;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.Sets;
15 import java.lang.ref.SoftReference;
16 import java.util.Collections;
17 import java.util.HashSet;
18 import java.util.Map;
19 import java.util.Set;
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.util.capability.Capability;
25 import org.opendaylight.controller.config.util.capability.ModuleListener;
26 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
27 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
28 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
33 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
34 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 public class YangStoreService implements YangStoreContext {
39
40     private static final Logger LOG = LoggerFactory.getLogger(YangStoreService.class);
41
42     /**
43      * This is a rather interesting locking model. We need to guard against both the
44      * cache expiring from GC and being invalidated by schema context change. The
45      * context can change while we are doing processing, so we do not want to block
46      * it, so no synchronization can happen on the methods.
47      *
48      * So what we are doing is the following:
49      *
50      * We synchronize with GC as usual, using a SoftReference.
51      *
52      * The atomic reference is used to synchronize with {@link #refresh(org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext)}, e.g. when
53      * refresh happens, it will push a SoftReference(null), e.g. simulate the GC. Now
54      * that may happen while the getter is already busy acting on the old schema context,
55      * so it needs to understand that a refresh has happened and retry. To do that, it
56      * attempts a CAS operation -- if it fails, in knows that the SoftReference has
57      * been replaced and thus it needs to retry.
58      *
59      * Note that {@link #getYangStoreSnapshot()} will still use synchronize() internally
60      * to stop multiple threads doing the same work.
61      */
62     private final AtomicReference<SoftReference<YangStoreSnapshot>> ref =
63             new AtomicReference<>(new SoftReference<YangStoreSnapshot>(null));
64
65     private final AtomicReference<SoftReference<BindingRuntimeContext>> refBindingContext =
66             new AtomicReference<>(new SoftReference<BindingRuntimeContext>(null));
67
68     private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
69
70     private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
71         @Override
72         public Thread newThread(final Runnable r) {
73             return new Thread(r, "yangstore-capability-notifications");
74         }
75     });
76
77     private final Set<ModuleListener> listeners = Collections.synchronizedSet(new HashSet<ModuleListener>());
78
79     public YangStoreService(final SchemaContextProvider schemaContextProvider,
80         final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
81         this.sourceProvider = sourceProvider;
82     }
83
84     synchronized YangStoreContext getYangStoreSnapshot() {
85         SoftReference<YangStoreSnapshot> r = ref.get();
86         YangStoreSnapshot ret = r.get();
87
88         while (ret == null) {
89             // We need to be compute a new value
90             // TODO sourceProvider is not a snapshot
91             ret = new YangStoreSnapshot(refBindingContext.get().get(), sourceProvider);
92
93             if (!ref.compareAndSet(r, new SoftReference<>(ret))) {
94                 LOG.debug("Concurrent refresh detected, recomputing snapshot");
95                 r = ref.get();
96                 ret = null;
97             }
98         }
99
100         return ret;
101     }
102
103     public YangStoreContext getCurrentSnapshot() {
104         return getYangStoreSnapshot();
105     }
106
107     @Deprecated
108     @Override
109     public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
110         return getYangStoreSnapshot().getModuleMXBeanEntryMap();
111     }
112
113     @Override
114     public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
115         return getYangStoreSnapshot().getQNamesToIdentitiesToModuleMXBeanEntries();
116     }
117
118     @Override
119     public Set<Module> getModules() {
120         return getYangStoreSnapshot().getModules();
121     }
122
123     @Override
124     public String getModuleSource(final ModuleIdentifier moduleIdentifier) {
125         return getYangStoreSnapshot().getModuleSource(moduleIdentifier);
126     }
127
128     @Override
129     public EnumResolver getEnumResolver() {
130         return getYangStoreSnapshot().getEnumResolver();
131     }
132
133     public void refresh(final BindingRuntimeContext runtimeContext) {
134         final YangStoreSnapshot previous = ref.get().get();
135         ref.set(new SoftReference<YangStoreSnapshot>(null));
136         refBindingContext.set(new SoftReference<>(runtimeContext));
137         notificationExecutor.submit(new CapabilityChangeNotifier(previous));
138     }
139
140     public AutoCloseable registerModuleListener(final ModuleListener listener) {
141         YangStoreContext context = ref.get().get();
142
143         if (context == null) {
144             context = getYangStoreSnapshot();
145         }
146
147         this.listeners.add(listener);
148         listener.onCapabilitiesChanged(toCapabilities(context.getModules(), context), Collections.<Capability>emptySet());
149
150         return new AutoCloseable() {
151             @Override
152             public void close() {
153                 YangStoreService.this.listeners.remove(listener);
154             }
155         };
156     }
157
158     private static Set<Capability> toCapabilities(final Set<Module> modules, final YangStoreContext current) {
159         return ImmutableSet.copyOf(Collections2.transform(modules, new Function<Module, Capability>() {
160             @Override
161             public Capability apply(final Module input) {
162                 return new YangModuleCapability(input, current.getModuleSource(input));
163             }
164         }));
165     }
166
167     private final class CapabilityChangeNotifier implements Runnable {
168
169         private final YangStoreSnapshot previous;
170
171         public CapabilityChangeNotifier(final YangStoreSnapshot previous) {
172             this.previous = previous;
173         }
174
175         @Override
176         public void run() {
177             final YangStoreContext current = getYangStoreSnapshot();
178
179             if (!current.equals(previous)) {
180                 final Set<Module> prevModules = previous.getModules();
181                 final Set<Module> currModules = current.getModules();
182                 final Set<Module> removed = Sets.difference(prevModules, currModules);
183                 final Set<Module> added = Sets.difference(currModules, prevModules);
184
185                 final Set<Capability> addedCaps = toCapabilities(added, current);
186                 final Set<Capability> removedCaps = toCapabilities(removed, current);
187
188                 for (final ModuleListener listener : listeners) {
189                     listener.onCapabilitiesChanged(addedCaps, removedCaps);
190                 }
191             }
192         }
193
194     }
195 }