Disconnect SchemaSourceListener from EventListener
[yangtools.git] / yang / yang-repo-spi / src / main / java / org / opendaylight / yangtools / yang / model / repo / spi / AbstractSchemaRepository.java
1 /*
2  * Copyright (c) 2014 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.yangtools.yang.model.repo.spi;
9
10 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ArrayListMultimap;
14 import com.google.common.collect.ListMultimap;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.io.Serializable;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import org.checkerframework.checker.lock.qual.GuardedBy;
28 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
29 import org.opendaylight.yangtools.concepts.Registration;
30 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
33 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Abstract base class for {@link SchemaRepository} implementations. It handles registration and lookup of schema
39  * sources, subclasses need only to provide their own {@link #createEffectiveModelContextFactory()} implementation.
40  */
41 @Beta
42 public abstract class AbstractSchemaRepository implements SchemaRepository, SchemaSourceRegistry {
43     private static final Logger LOG = LoggerFactory.getLogger(AbstractSchemaRepository.class);
44
45     /*
46      * Source identifier -> representation -> provider map. We usually are looking for
47      * a specific representation of a source.
48      */
49     @GuardedBy("this")
50     private final Map<SourceIdentifier, ListMultimap<Class<? extends SchemaSourceRepresentation>,
51             AbstractSchemaSourceRegistration<?>>> sources = new HashMap<>();
52
53     /*
54      * Schema source listeners.
55      */
56     @GuardedBy("this")
57     private final List<SchemaListenerRegistration> listeners = new ArrayList<>();
58
59     @SuppressWarnings("unchecked")
60     private static <T extends SchemaSourceRepresentation> ListenableFuture<T> fetchSource(
61             final SourceIdentifier id, final Iterator<AbstractSchemaSourceRegistration<?>> it) {
62         final AbstractSchemaSourceRegistration<?> reg = it.next();
63
64         return Futures.catchingAsync(((SchemaSourceProvider<T>)reg.getProvider()).getSource(id), Throwable.class,
65             input -> {
66                 LOG.debug("Failed to acquire source from {}", reg, input);
67
68                 if (it.hasNext()) {
69                     return fetchSource(id, it);
70                 }
71
72                 throw new MissingSchemaSourceException("All available providers exhausted", id, input);
73             }, MoreExecutors.directExecutor());
74     }
75
76     @Override
77     public <T extends SchemaSourceRepresentation> ListenableFuture<T> getSchemaSource(final SourceIdentifier id,
78             final Class<T> representation) {
79         final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations;
80
81         synchronized (this) {
82             final var srcs = sources.get(id);
83             if (srcs == null) {
84                 return immediateFailedFluentFuture(new MissingSchemaSourceException(
85                     "No providers registered for source " + id, id));
86             }
87
88             sortedSchemaSourceRegistrations = new ArrayList<>(srcs.get(representation));
89         }
90
91         // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
92         sortedSchemaSourceRegistrations.sort(SchemaProviderCostComparator.INSTANCE);
93
94         final var regs = sortedSchemaSourceRegistrations.iterator();
95         if (!regs.hasNext()) {
96             return immediateFailedFluentFuture(new MissingSchemaSourceException(
97                         "No providers for source " + id + " representation " + representation + " available", id));
98         }
99
100         final ListenableFuture<T> fetchSourceFuture = fetchSource(id, regs);
101         // Add callback to notify cache listeners about encountered schema
102         Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
103             @Override
104             public void onSuccess(final T result) {
105                 for (var listener : listeners) {
106                     listener.getInstance().schemaSourceEncountered(result);
107                 }
108             }
109
110             @Override
111             @SuppressWarnings("checkstyle:parameterName")
112             public void onFailure(final Throwable t) {
113                 LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
114             }
115         }, MoreExecutors.directExecutor());
116
117         return fetchSourceFuture;
118     }
119
120     private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source,
121             final AbstractSchemaSourceRegistration<T> reg) {
122         sources.computeIfAbsent(source.getSourceIdentifier(), ignored -> ArrayListMultimap.create())
123             .put(source.getRepresentation(), reg);
124
125         final var reps = Collections.<PotentialSchemaSource<?>>singleton(source);
126         for (var l : listeners) {
127             l.getInstance().schemaSourceRegistered(reps);
128         }
129     }
130
131     private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source,
132             final SchemaSourceRegistration<?> reg) {
133         final var m = sources.get(source.getSourceIdentifier());
134         if (m != null) {
135             m.remove(source.getRepresentation(), reg);
136
137             for (var l : listeners) {
138                 l.getInstance().schemaSourceUnregistered(source);
139             }
140
141             if (m.isEmpty()) {
142                 sources.remove(source.getSourceIdentifier());
143             }
144         }
145     }
146
147     @Override
148     public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(
149             final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
150         final var src = source.cachedReference();
151         final var ret = new AbstractSchemaSourceRegistration<>(provider, src) {
152             @Override
153             protected void removeRegistration() {
154                 removeSource(src, this);
155             }
156         };
157
158         addSource(src, ret);
159         return ret;
160     }
161
162     @Override
163     public Registration registerSchemaSourceListener(final SchemaSourceListener listener) {
164         final SchemaListenerRegistration ret = new SchemaListenerRegistration(listener);
165
166         synchronized (this) {
167             final var col = new ArrayList<PotentialSchemaSource<?>>();
168             for (var m : sources.values()) {
169                 for (var r : m.values()) {
170                     col.add(r.getInstance());
171                 }
172             }
173
174             // Notify first, so translator-type listeners, who react by registering a source
175             // do not cause infinite loop.
176             listener.schemaSourceRegistered(col);
177             listeners.add(ret);
178         }
179         return ret;
180     }
181
182     private final class SchemaListenerRegistration extends AbstractObjectRegistration<SchemaSourceListener> {
183         SchemaListenerRegistration(final SchemaSourceListener instance) {
184             super(instance);
185         }
186
187         @Override
188         protected void removeRegistration() {
189             listeners.remove(this);
190         }
191     }
192
193     private static final class SchemaProviderCostComparator implements Comparator<AbstractSchemaSourceRegistration<?>>,
194             Serializable {
195         static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
196
197         @java.io.Serial
198         private static final long serialVersionUID = 1L;
199
200         @Override
201         public int compare(final AbstractSchemaSourceRegistration<?> o1, final AbstractSchemaSourceRegistration<?> o2) {
202             return o1.getInstance().getCost() - o2.getInstance().getCost();
203         }
204
205         @java.io.Serial
206         private Object readResolve() {
207             return INSTANCE;
208         }
209     }
210 }