233545798fde3573dbd9169cf2c871da7259f64b
[controller.git] / opendaylight / config / config-manager-facade-xml / src / main / java / org / opendaylight / controller / config / facade / xml / osgi / YangStoreSnapshot.java
1 /*
2  * Copyright (c) 2015 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
9 package org.opendaylight.controller.config.facade.xml.osgi;
10
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.BiMap;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Sets;
17 import com.google.common.io.ByteStreams;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.lang.ref.SoftReference;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Objects;
27 import java.util.Set;
28 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
29 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
30 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
31 import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
32 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
33 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.Module;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
39 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 final class YangStoreSnapshot implements YangStoreContext, EnumResolver {
46     private static final class MXBeans {
47         private final Map<String /* Namespace from yang file */,
48                 Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
49         private final Map<QName, Map<String, ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries;
50
51         MXBeans(final SchemaContext schemaContext) {
52             LOG.trace("Resolved modules:{}", schemaContext.getModules());
53
54             // JMX generator
55             Map<String, String> namespaceToPackageMapping = Maps.newHashMap();
56             PackageTranslator packageTranslator = new PackageTranslator(namespaceToPackageMapping);
57             Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
58             Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>();
59             // create SIE structure qNamesToSIEs
60             for (Module module : schemaContext.getModules()) {
61                 String packageName = packageTranslator.getPackageName(module);
62                 Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
63                         .create(module, packageName, knownSEITracker);
64                 for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries.entrySet()) {
65                     // merge value into qNamesToSIEs
66                     if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
67                         qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
68                     } else {
69                         throw new IllegalStateException("Cannot add two SIE with same qname "
70                                 + sieEntry.getValue());
71                     }
72                 }
73             }
74
75             Map<String, Map<String, ModuleMXBeanEntry>> moduleMXBeanEntryMap = Maps.newHashMap();
76
77             Map<QName, Map<String /* identity local name */, ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries = new HashMap<>();
78
79
80             for (Module module : schemaContext.getModules()) {
81                 String packageName = packageTranslator.getPackageName(module);
82                 TypeProviderWrapper typeProviderWrapper = new TypeProviderWrapper(
83                         new TypeProviderImpl(schemaContext));
84
85                 QName qName = QName.create(module.getNamespace(), module.getRevision(), module.getName());
86
87                 Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs =
88                         Collections.unmodifiableMap(ModuleMXBeanEntry.create(module, qNamesToSIEs, schemaContext,
89                                 typeProviderWrapper, packageName));
90                 moduleMXBeanEntryMap.put(module.getNamespace().toString(), namesToMBEs);
91
92                 qNamesToIdentitiesToModuleMXBeanEntries.put(qName, namesToMBEs);
93             }
94             this.moduleMXBeanEntryMap = Collections.unmodifiableMap(moduleMXBeanEntryMap);
95             this.qNamesToIdentitiesToModuleMXBeanEntries = Collections.unmodifiableMap(qNamesToIdentitiesToModuleMXBeanEntries);
96         }
97     }
98
99     private static final Logger LOG = LoggerFactory.getLogger(YangStoreSnapshot.class);
100     private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
101     private final BindingRuntimeContext bindingContextProvider;
102
103     /**
104      * We want to lazily compute the context of the MXBean class and have it only softly-attached to this instance,
105      * so it can be garbage collected when the memory gets tight. If the schema context changes as we are computing
106      * things, YangStoreService will detect that and retry, so we do not have to worry about that.
107      */
108     private volatile SoftReference<MXBeans> ref = new SoftReference<>(null);
109
110     public YangStoreSnapshot(final BindingRuntimeContext bindingContextProvider,
111         final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
112         this.bindingContextProvider = Preconditions.checkNotNull(bindingContextProvider);
113         this.sourceProvider = Preconditions.checkNotNull(sourceProvider);
114     }
115
116     private MXBeans getMXBeans() {
117         MXBeans mxBean = ref.get();
118
119         if (mxBean == null) {
120             synchronized (this) {
121                 mxBean = ref.get();
122                 if (mxBean == null) {
123                     mxBean = new MXBeans(bindingContextProvider.getSchemaContext());
124                     ref = new SoftReference<>(mxBean);
125                 }
126             }
127         }
128
129         return mxBean;
130     }
131
132     @Override
133     public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
134         return getMXBeans().moduleMXBeanEntryMap;
135     }
136
137     @Override
138     public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
139         return getMXBeans().qNamesToIdentitiesToModuleMXBeanEntries;
140     }
141
142     @Override
143     public Set<Module> getModules() {
144         final Set<Module> modules = Sets.newHashSet(bindingContextProvider.getSchemaContext().getModules());
145         for (final Module module : bindingContextProvider.getSchemaContext().getModules()) {
146             modules.addAll(module.getSubmodules());
147         }
148         return modules;
149     }
150
151     @Override
152     public String getModuleSource(final org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
153         final CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source = sourceProvider.getSource(
154             SourceIdentifier.create(moduleIdentifier.getName(), Optional.fromNullable(
155                 QName.formattedRevision(moduleIdentifier.getRevision()))));
156
157         try {
158             final YangTextSchemaSource yangTextSchemaSource = source.checkedGet();
159             try(InputStream inStream = yangTextSchemaSource.openStream()) {
160                 return new String(ByteStreams.toByteArray(inStream), Charsets.UTF_8);
161             }
162         } catch (SchemaSourceException | IOException e) {
163             LOG.warn("Unable to provide source for {}", moduleIdentifier, e);
164             throw new IllegalArgumentException("Unable to provide source for " + moduleIdentifier, e);
165         }
166     }
167
168     @Override
169     public EnumResolver getEnumResolver() {
170         return this;
171     }
172
173     @Override
174     public boolean equals(final Object obj) {
175         if (this == obj) {
176             return true;
177         }
178         if (!(obj instanceof YangStoreSnapshot)) {
179             return false;
180         }
181
182         final YangStoreSnapshot other = (YangStoreSnapshot) obj;
183         return Objects.equals(bindingContextProvider, other.bindingContextProvider);
184     }
185
186     @Override
187     public int hashCode() {
188         return Objects.hashCode(bindingContextProvider);
189     }
190
191     @Override
192     public String fromYang(final String enumClass, final String enumYangValue) {
193         Preconditions.checkState(bindingContextProvider != null, "Binding context provider was not set yet");
194         final BiMap<String, String> enumMapping = bindingContextProvider.getEnumMapping(enumClass);
195         final String javaName = enumMapping.get(enumYangValue);
196         return Preconditions.checkNotNull(javaName, "Unable to resolve enum value %s for enum class %s with assumed enum mapping: %s", enumYangValue, enumClass, enumMapping);
197     }
198
199     @Override
200     public String toYang(final String enumClass, final String enumJavaValue) {
201         Preconditions.checkState(bindingContextProvider != null, "Binding context provider was not set yet");
202         final BiMap<String, String> enumMapping = bindingContextProvider.getEnumMapping(enumClass);
203         final String javaName = enumMapping.inverse().get(enumJavaValue);
204         return Preconditions.checkNotNull(javaName,
205             "Unable to map enum value %s for enum class %s with assumed enum mapping: %s", enumJavaValue, enumClass,
206             enumMapping.inverse());
207     }
208 }