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