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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.