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