BUG-997: Evolve the SchemaRegistry concepts
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / SharedSchemaContextFactory.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.parser.repo;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.Cache;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Maps;
16 import com.google.common.util.concurrent.AsyncFunction;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21
22 import java.util.Collection;
23 import java.util.LinkedHashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27
28 import org.antlr.v4.runtime.ParserRuleContext;
29 import org.antlr.v4.runtime.tree.ParseTreeWalker;
30 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
31 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
36 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
37 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
38 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
39 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
40 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
41 import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
42 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 final class SharedSchemaContextFactory implements SchemaContextFactory {
47     private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper.create("resolve sources", SchemaResolutionException.class);
48     private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
49
50     private final Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>> requestSources = new Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>>() {
51         @Override
52         public ListenableFuture<ASTSchemaSource> apply(final SourceIdentifier input) {
53             return repository.getSchemaSource(input, ASTSchemaSource.class);
54         }
55     };
56     private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().softValues().build();
57
58     private final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources = new AsyncFunction<List<ASTSchemaSource>, SchemaContext>() {
59         @Override
60         public ListenableFuture<SchemaContext> apply(final List<ASTSchemaSource> sources) throws SchemaResolutionException {
61             final Map<SourceIdentifier, ASTSchemaSource> srcs =
62                     Maps.uniqueIndex(sources, ASTSchemaSource.GET_IDENTIFIER);
63             final Map<SourceIdentifier, YangModelDependencyInfo> deps =
64                     Maps.transformValues(srcs, ASTSchemaSource.GET_DEPINFO);
65
66             LOG.debug("Resolving dependency reactor {}", deps);
67
68             final DependencyResolver res = DependencyResolver.create(deps);
69             if (!res.getUnresolvedSources().isEmpty()) {
70                 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(), res.getUnsatisfiedImports());
71
72                 // FIXME: push into DependencyResolver
73
74                 throw new SchemaResolutionException("Failed to resolve required models",
75                         res.getResolvedSources(), res.getUnsatisfiedImports());
76             }
77
78             final Map<SourceIdentifier, ParserRuleContext> asts =
79                     Maps.transformValues(srcs, ASTSchemaSource.GET_AST);
80
81             final ParseTreeWalker walker = new ParseTreeWalker();
82             final Map<SourceIdentifier, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
83
84             for (Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
85                 ModuleBuilder moduleBuilder =
86                         YangParserListenerImpl.create(entry.getKey().getName(), walker, entry.getValue()).getModuleBuilder();
87
88                 moduleBuilder.setSource(srcs.get(entry.getKey()).getYangText());
89                 sourceToBuilder.put(entry.getKey(), moduleBuilder);
90             }
91             LOG.debug("Modules ready for integration");
92
93             final YangParserImpl parser = YangParserImpl.getInstance();
94             final Collection<Module> modules = parser.buildModules(sourceToBuilder.values());
95             LOG.debug("Integrated cross-references modules");
96             return Futures.immediateCheckedFuture(parser.assembleContext(modules));
97         }
98     };
99
100     private final SharedSchemaRepository repository;
101     // FIXME: ignored right now
102     private final SchemaSourceFilter filter;
103
104     public SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
105         this.repository = Preconditions.checkNotNull(repository);
106         this.filter = Preconditions.checkNotNull(filter);
107     }
108
109     @Override
110     public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(final Collection<SourceIdentifier> requiredSources) {
111         final SchemaContext existing = cache.getIfPresent(requiredSources);
112         if (existing != null) {
113             LOG.debug("Returning cached context {}", existing);
114             return Futures.immediateCheckedFuture(existing);
115         }
116
117         // Request all sources be loaded
118         final ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(requiredSources, requestSources));
119
120         // Assemble sources into a schemacontext
121         final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);
122
123         // Populate cache when successful
124         Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
125             @Override
126             public void onSuccess(final SchemaContext result) {
127                 cache.put(requiredSources, result);
128             }
129
130             @Override
131             public void onFailure(final Throwable t) {
132                 LOG.info("Failed to assemble sources", t);
133             }
134         });
135
136         return Futures.makeChecked(cf, MAPPER);
137     }
138 }