Merge "Bug 1025: Fixed incorrect revision in sal-remote-augment, which caused log...
[controller.git] / opendaylight / netconf / config-netconf-connector / src / main / java / org / opendaylight / controller / netconf / confignetconfconnector / mapping / config / Config.java
1 /*
2  * Copyright (c) 2013 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.netconf.confignetconfconnector.mapping.config;
10
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.HashMultimap;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Multimap;
19
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Date;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27
28 import javax.management.ObjectName;
29
30 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
31 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
32 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
33 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
34 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
35 import org.opendaylight.controller.netconf.util.xml.XmlElement;
36 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.Element;
39
40
41 public class Config {
42
43     private final Map<String/* Namespace from yang file */,
44             Map<String /* Name of module entry from yang file */, ModuleConfig>> moduleConfigs;
45
46     private final Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap;
47
48     public Config(Map<String, Map<String, ModuleConfig>> moduleConfigs) {
49         this(moduleConfigs, Collections.<String, Map<Date, EditConfig.IdentityMapping>>emptyMap());
50     }
51
52     public Config(Map<String, Map<String, ModuleConfig>> moduleConfigs, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) {
53         this.moduleConfigs = moduleConfigs;
54         this.identityMap = identityMap;
55     }
56
57     public static Map<String, Map<String, Collection<ObjectName>>> getMappedInstances(Set<ObjectName> instancesToMap,
58                                                                                 Map<String, Map<String, ModuleConfig>> configs) {
59         Multimap<String, ObjectName> moduleToInstances = mapInstancesToModules(instancesToMap);
60
61         Map<String, Map<String, Collection<ObjectName>>> retVal = Maps.newLinkedHashMap();
62
63         for (Entry<String, Map<String, ModuleConfig>> namespaceToModuleToConfigEntry : configs.entrySet()) {
64
65             Map<String, Collection<ObjectName>> innerRetVal = Maps.newHashMap();
66
67             for (Entry<String, ModuleConfig> mbeEntry : namespaceToModuleToConfigEntry.getValue().entrySet()) {
68
69                 String moduleName = mbeEntry.getKey();
70                 Collection<ObjectName> instances = moduleToInstances.get(moduleName);
71
72                 // TODO, this code does not support same module names from different namespaces
73                 // Namespace should be present in ObjectName
74
75                 if (instances == null){
76                     continue;
77                 }
78
79                 innerRetVal.put(moduleName, instances);
80
81             }
82
83             retVal.put(namespaceToModuleToConfigEntry.getKey(), innerRetVal);
84         }
85         return retVal;
86     }
87
88     private static Multimap<String, ObjectName> mapInstancesToModules(Set<ObjectName> instancesToMap) {
89         Multimap<String, ObjectName> retVal = HashMultimap.create();
90
91         for (ObjectName objectName : instancesToMap) {
92             String factoryName = ObjectNameUtil.getFactoryName(objectName);
93             retVal.put(factoryName, objectName);
94         }
95         return retVal;
96     }
97
98     public Element toXml(Set<ObjectName> instancesToMap, Optional<String> maybeNamespace, Document document,
99             Element dataElement, ServiceRegistryWrapper serviceTracker) {
100
101         Map<String, Map<String, Collection<ObjectName>>> moduleToInstances = getMappedInstances(instancesToMap,
102                 moduleConfigs);
103
104         if (maybeNamespace.isPresent()) {
105             dataElement.setAttributeNS(maybeNamespace.get(), dataElement.getNodeName(), "xmlns");
106         }
107
108         Element modulesElement = XmlUtil.createElement(document, XmlNetconfConstants.MODULES_KEY, Optional.of(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
109         dataElement.appendChild(modulesElement);
110         for (Entry<String, Map<String, Collection<ObjectName>>> moduleToInstanceEntry : moduleToInstances.entrySet()) {
111             for (Entry<String, Collection<ObjectName>> moduleMappingEntry : moduleToInstanceEntry.getValue()
112                     .entrySet()) {
113
114                 ModuleConfig mapping = moduleConfigs.get(moduleToInstanceEntry.getKey()).get(moduleMappingEntry.getKey());
115
116                 if (moduleMappingEntry.getValue().isEmpty()) {
117                     continue;
118                 }
119
120                 for (ObjectName objectName : moduleMappingEntry.getValue()) {
121                     modulesElement.appendChild(mapping.toXml(objectName, document, moduleToInstanceEntry.getKey()));
122                 }
123
124             }
125         }
126
127         dataElement.appendChild(Services.toXml(serviceTracker, document));
128
129         return dataElement;
130     }
131
132     // TODO refactor, replace string representing namespace with namespace class
133     // TODO refactor, replace Map->Multimap with e.g. ConfigElementResolved
134     // class
135
136     public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(XmlElement xml, EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws NetconfDocumentedException {
137         Optional<XmlElement> modulesElement = getModulesElement(xml);
138         List<XmlElement> moduleElements = getModulesElementList(modulesElement);
139
140         Map<String, Multimap<String, ModuleElementResolved>> retVal = Maps.newHashMap();
141
142         for (XmlElement moduleElement : moduleElements) {
143             ResolvingStrategy<ModuleElementResolved> resolvingStrategy = new ResolvingStrategy<ModuleElementResolved>() {
144                 @Override
145                 public ModuleElementResolved resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker, String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws NetconfDocumentedException {
146                     return moduleMapping.fromXml(moduleElement, serviceTracker,
147                             instanceName, moduleNamespace, defaultStrategy, identityMap);
148                 }
149             };
150
151             resolveModule(retVal, serviceTracker, moduleElement, defaultEditStrategyType, resolvingStrategy);
152         }
153         return retVal;
154     }
155
156     /**
157      * return a map containing namespace -> moduleName -> instanceName map. Attribute parsing is omitted.
158      */
159     public Map<String, Multimap<String, ModuleElementDefinition>> fromXmlModulesMap(XmlElement xml,
160             EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws NetconfDocumentedException {
161         Optional<XmlElement> modulesElement = getModulesElement(xml);
162         List<XmlElement> moduleElements = getModulesElementList(modulesElement);
163
164         Map<String, Multimap<String, ModuleElementDefinition>> retVal = Maps.newHashMap();
165
166         for (XmlElement moduleElement : moduleElements) {
167             ResolvingStrategy<ModuleElementDefinition> resolvingStrategy = new ResolvingStrategy<ModuleElementDefinition>() {
168                 @Override
169                 public ModuleElementDefinition resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement,
170                         ServiceRegistryWrapper serviceTracker, String instanceName, String moduleNamespace,
171                         EditStrategyType defaultStrategy) {
172                     // TODO: add check for conflicts between global and local
173                     // edit strategy
174                     String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
175                             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
176                     return new ModuleElementDefinition(instanceName, perInstanceEditStrategy, defaultStrategy);
177                 }
178             };
179
180             resolveModule(retVal, serviceTracker, moduleElement, defaultEditStrategyType, resolvingStrategy);
181         }
182         return retVal;
183     }
184
185     private static Optional<XmlElement> getModulesElement(XmlElement xml) {
186         return xml.getOnlyChildElementOptionally(XmlNetconfConstants.MODULES_KEY,
187                     XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
188     }
189
190     private List<XmlElement> getModulesElementList(Optional<XmlElement> modulesElement) throws NetconfDocumentedException {
191         List<XmlElement> moduleElements;
192
193         if (modulesElement.isPresent()) {
194             moduleElements = modulesElement.get().getChildElementsWithSameNamespace(XmlNetconfConstants.MODULE_KEY);
195             modulesElement.get().checkUnrecognisedElements(moduleElements);
196         } else {
197             moduleElements = Lists.newArrayList();
198         }
199         return moduleElements;
200     }
201
202     private <T> void resolveModule(Map<String, Multimap<String, T>> retVal, ServiceRegistryWrapper serviceTracker,
203             XmlElement moduleElement, EditStrategyType defaultStrategy, ResolvingStrategy<T> resolvingStrategy) throws NetconfDocumentedException {
204         XmlElement typeElement = null;
205         typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
206         Entry<String, String> prefixToNamespace = typeElement.findNamespaceOfTextContent();
207         String moduleNamespace = prefixToNamespace.getValue();
208         XmlElement nameElement = null;
209         nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
210         String instanceName = nameElement.getTextContent();
211         String factoryNameWithPrefix = typeElement.getTextContent();
212         String prefixOrEmptyString = prefixToNamespace.getKey();
213         String factoryName = getFactoryName(factoryNameWithPrefix, prefixOrEmptyString);
214
215         ModuleConfig moduleMapping = getModuleMapping(moduleNamespace, instanceName, factoryName);
216
217         Multimap<String, T> innerMap = retVal.get(moduleNamespace);
218         if (innerMap == null) {
219             innerMap = HashMultimap.create();
220             retVal.put(moduleNamespace, innerMap);
221         }
222
223         T resolvedElement = resolvingStrategy.resolveElement(moduleMapping, moduleElement, serviceTracker,
224                 instanceName, moduleNamespace, defaultStrategy);
225
226         innerMap.put(factoryName, resolvedElement);
227     }
228
229     public Services fromXmlServices(XmlElement xml) throws NetconfDocumentedException {
230         Optional<XmlElement> servicesElement = getServicesElement(xml);
231
232         Services services;
233         if (servicesElement.isPresent()) {
234             services = Services.fromXml(servicesElement.get());
235         } else {
236             services = new Services();
237         }
238
239         return services;
240     }
241
242     private static Optional<XmlElement> getServicesElement(XmlElement xml) {
243         return xml.getOnlyChildElementOptionally(XmlNetconfConstants.SERVICES_KEY,
244                     XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
245     }
246
247     public static void checkUnrecognisedChildren(XmlElement parent) throws NetconfDocumentedException {
248         Optional<XmlElement> servicesOpt = getServicesElement(parent);
249         Optional<XmlElement> modulesOpt = getModulesElement(parent);
250
251         List<XmlElement> recognised = Lists.newArrayList();
252         if(servicesOpt.isPresent()){
253             recognised.add(servicesOpt.get());
254         }
255         if(modulesOpt.isPresent()){
256             recognised.add(modulesOpt.get());
257         }
258
259         parent.checkUnrecognisedElements(recognised);
260     }
261
262     private String getFactoryName(String factoryNameWithPrefix, String prefixOrEmptyString) {
263         checkState(
264                 factoryNameWithPrefix.startsWith(prefixOrEmptyString),
265                 String.format("Internal error: text " + "content '%s' of type node does not start with prefix '%s'",
266                         factoryNameWithPrefix, prefixOrEmptyString));
267
268         int factoryNameAfterPrefixIndex;
269         if (prefixOrEmptyString.isEmpty()) {
270             factoryNameAfterPrefixIndex = 0;
271         } else {
272             factoryNameAfterPrefixIndex = prefixOrEmptyString.length() + 1;
273         }
274         return factoryNameWithPrefix.substring(factoryNameAfterPrefixIndex);
275     }
276
277     private ModuleConfig getModuleMapping(String moduleNamespace, String instanceName, String factoryName) {
278         Map<String, ModuleConfig> mappingsFromNamespace = moduleConfigs.get(moduleNamespace);
279
280         Preconditions.checkNotNull(mappingsFromNamespace,
281                 "Namespace %s, defined in: module %s of type %s not found, available namespaces: %s", moduleNamespace,
282                 instanceName, factoryName, moduleConfigs.keySet());
283
284         ModuleConfig moduleMapping = mappingsFromNamespace.get(factoryName);
285         checkState(moduleMapping != null, "Cannot find mapping for module type " + factoryName);
286         return moduleMapping;
287     }
288
289     private interface ResolvingStrategy<T> {
290         public T resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker,
291                 String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws NetconfDocumentedException;
292     }
293 }