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