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