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