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