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