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