Expose yang source provider into config subsystem
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / sal / dom / broker / GlobalBundleScanningSchemaServiceImpl.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 package org.opendaylight.controller.sal.dom.broker;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import java.net.URL;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Enumeration;
22 import java.util.List;
23 import java.util.concurrent.atomic.AtomicReference;
24 import javax.annotation.concurrent.GuardedBy;
25 import org.opendaylight.controller.sal.core.api.model.SchemaService;
26 import org.opendaylight.controller.sal.core.api.model.YangTextSourceProvider;
27 import org.opendaylight.yangtools.concepts.ListenerRegistration;
28 import org.opendaylight.yangtools.concepts.Registration;
29 import org.opendaylight.yangtools.util.ListenerRegistry;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
37 import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
38 import org.osgi.framework.Bundle;
39 import org.osgi.framework.BundleContext;
40 import org.osgi.framework.BundleEvent;
41 import org.osgi.framework.ServiceReference;
42 import org.osgi.util.tracker.BundleTracker;
43 import org.osgi.util.tracker.BundleTrackerCustomizer;
44 import org.osgi.util.tracker.ServiceTracker;
45 import org.osgi.util.tracker.ServiceTrackerCustomizer;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, YangTextSourceProvider, AutoCloseable {
50     private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
51
52     private static AtomicReference<GlobalBundleScanningSchemaServiceImpl> globalInstance = new AtomicReference<>();
53
54     @GuardedBy(value = "lock")
55     private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
56     private final URLSchemaContextResolver contextResolver = URLSchemaContextResolver.create("global-bundle");
57     private final BundleScanner scanner = new BundleScanner();
58     private final BundleContext context;
59
60     private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
61     private BundleTracker<Iterable<Registration>> bundleTracker;
62     private boolean starting = true;
63     private volatile boolean stopping;
64     private final Object lock = new Object();
65
66     private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
67         this.context = Preconditions.checkNotNull(context);
68     }
69
70     public static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) {
71         GlobalBundleScanningSchemaServiceImpl instance = new GlobalBundleScanningSchemaServiceImpl(ctx);
72         Preconditions.checkState(globalInstance.compareAndSet(null, instance));
73         instance.start();
74         return instance;
75     }
76
77     public static GlobalBundleScanningSchemaServiceImpl getInstance() {
78         GlobalBundleScanningSchemaServiceImpl instance = globalInstance.get();
79         Preconditions.checkState(instance != null, "Global Instance was not instantiated");
80         return instance;
81     }
82
83     @VisibleForTesting
84     public static void destroyInstance() {
85         GlobalBundleScanningSchemaServiceImpl instance = globalInstance.getAndSet(null);
86         if(instance != null) {
87             instance.close();
88         }
89     }
90
91     public BundleContext getContext() {
92         return context;
93     }
94
95     public void start() {
96         checkState(context != null);
97         LOG.debug("start() starting");
98
99         listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, GlobalBundleScanningSchemaServiceImpl.this);
100         bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING |
101                 Bundle.STOPPING | Bundle.ACTIVE, scanner);
102
103         synchronized(lock) {
104             bundleTracker.open();
105
106             LOG.debug("BundleTracker.open() complete");
107
108             boolean hasExistingListeners = Iterables.size(listeners.getListeners()) > 0;
109             if(hasExistingListeners) {
110                 tryToUpdateSchemaContext();
111             }
112         }
113
114         listenerTracker.open();
115         starting = false;
116
117         LOG.debug("start() complete");
118     }
119
120     @Override
121     public SchemaContext getSchemaContext() {
122         return getGlobalContext();
123     }
124
125     @Override
126     public SchemaContext getGlobalContext() {
127         return contextResolver.getSchemaContext().orNull();
128     }
129
130     @Override
131     public void addModule(final Module module) {
132         throw new UnsupportedOperationException();
133     }
134
135     @Override
136     public SchemaContext getSessionContext() {
137         throw new UnsupportedOperationException();
138     }
139
140     @Override
141     public void removeModule(final Module module) {
142         throw new UnsupportedOperationException();
143     }
144
145     @Override
146     public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
147         synchronized(lock) {
148             Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
149             if(potentialCtx.isPresent()) {
150                 listener.onGlobalContextUpdated(potentialCtx.get());
151             }
152             return listeners.register(listener);
153         }
154     }
155
156     @Override
157     public void close() {
158         stopping = true;
159         if (bundleTracker != null) {
160             bundleTracker.close();
161         }
162         if (listenerTracker != null) {
163             listenerTracker.close();
164         }
165
166         for (ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
167             l.close();
168         }
169     }
170
171     @GuardedBy(value = "lock")
172     private void notifyListeners(final SchemaContext snapshot) {
173         Object[] services = listenerTracker.getServices();
174         for (ListenerRegistration<SchemaContextListener> listener : listeners) {
175             try {
176                 listener.getInstance().onGlobalContextUpdated(snapshot);
177             } catch (Exception e) {
178                 LOG.error("Exception occured during invoking listener", e);
179             }
180         }
181         if (services != null) {
182             for (Object rawListener : services) {
183                 final SchemaContextListener listener = (SchemaContextListener) rawListener;
184                 try {
185                     listener.onGlobalContextUpdated(snapshot);
186                 } catch (Exception e) {
187                     LOG.error("Exception occured during invoking listener {}", listener, e);
188                 }
189             }
190         }
191     }
192
193     @Override
194     public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
195         return contextResolver.getSource(sourceIdentifier);
196
197     }
198
199     private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
200         @Override
201         public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
202
203             if (bundle.getBundleId() == 0) {
204                 return Collections.emptyList();
205             }
206
207             final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
208             if (enumeration == null) {
209                 return Collections.emptyList();
210             }
211
212             final List<Registration> urls = new ArrayList<>();
213             while (enumeration.hasMoreElements()) {
214                 final URL u = enumeration.nextElement();
215                 try {
216                     urls.add(contextResolver.registerSource(u));
217                     LOG.debug("Registered {}", u);
218                 } catch (Exception e) {
219                     LOG.warn("Failed to register {}, ignoring it", e);
220                 }
221             }
222
223             if (!urls.isEmpty()) {
224                 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
225                         urls.size(), bundle.getSymbolicName());
226                 tryToUpdateSchemaContext();
227             }
228
229             return ImmutableList.copyOf(urls);
230         }
231
232         @Override
233         public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
234         }
235
236         /**
237          * If removing YANG files makes yang store inconsistent, method
238          * {@link #getYangStoreSnapshot()} will throw exception. There is no
239          * rollback.
240          */
241
242         @Override
243         public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
244             for (Registration url : urls) {
245                 try {
246                     url.close();
247                 } catch (Exception e) {
248                     LOG.warn("Failed do unregister URL {}, proceeding", url, e);
249                 }
250             }
251
252             int numUrls = Iterables.size(urls);
253             if(numUrls > 0 ) {
254                 if(LOG.isDebugEnabled()) {
255                     LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(), bundle.getState(), numUrls);
256                 }
257
258                 tryToUpdateSchemaContext();
259             }
260         }
261     }
262
263     @Override
264     public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
265
266         SchemaContextListener listener = context.getService(reference);
267         SchemaContext _ctxContext = getGlobalContext();
268         if (getContext() != null && _ctxContext != null) {
269             listener.onGlobalContextUpdated(_ctxContext);
270         }
271         return listener;
272     }
273
274     public void tryToUpdateSchemaContext() {
275         if (starting || stopping) {
276             return;
277         }
278
279         synchronized(lock) {
280             Optional<SchemaContext> schema = contextResolver.getSchemaContext();
281             if(schema.isPresent()) {
282                 if(LOG.isDebugEnabled()) {
283                     LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
284                 }
285
286                 notifyListeners(schema.get());
287             }
288         }
289     }
290
291     @Override
292     public void modifiedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
293         // NOOP
294     }
295
296     @Override
297     public void removedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
298         context.ungetService(reference);
299     }
300 }