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