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