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