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