2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
11 import com.google.common.base.Optional;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Maps;
15 import java.util.Date;
16 import java.util.List;
18 import java.util.Map.Entry;
20 import javax.management.ObjectName;
21 import javax.management.openmbean.OpenType;
23 import org.opendaylight.controller.config.util.ConfigRegistryClient;
24 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
25 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
26 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
28 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
29 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
30 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
31 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
32 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
33 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
34 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.ObjectResolver;
35 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.AttributeWritingStrategy;
36 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
37 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
38 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
39 import org.opendaylight.controller.netconf.util.xml.XmlElement;
40 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
46 public final class InstanceConfig {
47 private static final Logger logger = LoggerFactory.getLogger(InstanceConfig.class);
49 private final Map<String, AttributeIfc> yangToAttrConfig;
50 private final String nullableDummyContainerName;
51 private final Map<String, AttributeIfc> jmxToAttrConfig;
52 private final ConfigRegistryClient configRegistryClient;
54 public InstanceConfig(ConfigRegistryClient configRegistryClient, Map<String, AttributeIfc> yangNamesToAttributes,
55 String nullableDummyContainerName) {
57 this.yangToAttrConfig = yangNamesToAttributes;
58 this.nullableDummyContainerName = nullableDummyContainerName;
59 this.jmxToAttrConfig = reverseMap(yangNamesToAttributes);
60 this.configRegistryClient = configRegistryClient;
63 private Map<String, Object> getMappedConfiguration(ObjectName on) {
65 // TODO make field, mappingStrategies can be instantiated only once
66 Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> mappingStrategies = new ObjectMapper()
67 .prepareMapping(jmxToAttrConfig);
69 Map<String, Object> toXml = Maps.newHashMap();
71 for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
72 // Skip children runtime beans as they are mapped by InstanceRuntime
73 if (configDefEntry.getValue() instanceof RuntimeBeanEntry){
76 Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
78 AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
79 .get(configDefEntry.getKey());
80 Optional<?> a = attributeMappingStrategy.mapAttribute(value);
84 toXml.put(configDefEntry.getValue().getAttributeYangName(), a.get());
85 } catch (Exception e) {
86 throw new IllegalStateException("Unable to map value " + value + " to attribute "
87 + configDefEntry.getKey(), e);
93 public Element toXml(ObjectName on, String namespace, Document document, Element rootElement) {
94 Map<String, AttributeWritingStrategy> strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document);
95 Map<String, Object> mappedConfig = getMappedConfiguration(on);
96 Element parentElement;
97 if (nullableDummyContainerName != null) {
98 Element dummyElement = XmlUtil.createElement(document, nullableDummyContainerName, Optional.of(namespace));
99 rootElement.appendChild(dummyElement);
100 parentElement = dummyElement;
102 parentElement = rootElement;
104 for (Entry<String, ?> mappingEntry : mappedConfig.entrySet()) {
106 strats.get(mappingEntry.getKey()).writeElement(parentElement, namespace, mappingEntry.getValue());
107 } catch (Exception e) {
108 throw new IllegalStateException("Unable to write value " + mappingEntry.getValue() + " for attribute "
109 + mappingEntry.getValue(), e);
115 private void resolveConfiguration(InstanceConfigElementResolved mappedConfig, ServiceRegistryWrapper depTracker) {
117 // TODO make field, resolvingStrategies can be instantiated only once
118 Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(
119 depTracker).prepareResolving(yangToAttrConfig);
121 for (Entry<String, AttributeConfigElement> configDefEntry : mappedConfig.getConfiguration().entrySet()) {
122 AttributeConfigElement value = configDefEntry.getValue();
123 String attributeName = configDefEntry.getKey();
125 AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
127 logger.trace("Trying to set value {} of attribute {} with {}", value, attributeName, attributeResolvingStrategy);
129 value.resolveValue(attributeResolvingStrategy, attributeName);
131 yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
132 } catch (Exception e) {
133 throw new IllegalStateException("Unable to resolve value " + value
134 + " to attribute " + attributeName, e);
139 public InstanceConfigElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper services, String moduleNamespace,
140 EditStrategyType defaultStrategy,
141 Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) throws NetconfDocumentedException {
142 Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
144 Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
145 List<XmlElement> recognisedChildren = Lists.newArrayList();
147 XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
148 XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
149 List<XmlElement> typeAndNameElements = Lists.newArrayList(typeElement, nameElement);
151 // if dummy container was defined in yang, set moduleElement to its content
152 if (nullableDummyContainerName != null) {
153 int size = moduleElement.getChildElements().size();
154 int expectedChildNodes = 1 + typeAndNameElements.size();
155 if (size > expectedChildNodes) {
156 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
157 nameElement.getTextContent() + " - Expected " + expectedChildNodes +" child nodes, " +
158 "one of them with name " + nullableDummyContainerName +
159 ", got " + size + " elements.");
161 if (size == expectedChildNodes) {
163 moduleElement = moduleElement.getOnlyChildElement(nullableDummyContainerName, moduleNamespace);
164 } catch (NetconfDocumentedException e) {
165 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
166 nameElement.getTextContent() + " - Expected child node with name " + nullableDummyContainerName +
167 "." + e.getMessage());
169 } // else 2 elements, no need to descend
172 for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
173 List<XmlElement> configNodes = getConfigNodes(moduleElement, moduleNamespace, readStratEntry.getKey(),
174 recognisedChildren, typeAndNameElements);
175 AttributeConfigElement readElement = readStratEntry.getValue().readElement(configNodes);
176 retVal.put(readStratEntry.getKey(), readElement);
179 recognisedChildren.addAll(typeAndNameElements);
181 moduleElement.checkUnrecognisedElements(recognisedChildren);
182 } catch (NetconfDocumentedException e) {
183 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
184 nameElement.getTextContent() + " - " +
185 e.getMessage(), e.getErrorType(), e.getErrorTag(),e.getErrorSeverity(),e.getErrorInfo());
187 // TODO: add check for conflicts between global and local edit strategy
188 String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
189 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
191 InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("") ? new InstanceConfigElementResolved(
192 retVal, defaultStrategy) : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
194 resolveConfiguration(instanceConfigElementResolved, services);
195 return instanceConfigElementResolved;
198 private List<XmlElement> getConfigNodes(XmlElement moduleElement, String moduleNamespace, String name,
199 List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws NetconfDocumentedException {
200 List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
201 if (foundConfigNodes.isEmpty()) {
202 logger.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
203 logger.debug("Trying lookup of config nodes without specified namespace");
204 foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name,
205 XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
206 // In case module type or name element is not present in config it
207 // would be matched with config type or name
208 // We need to remove config type and name from available module
210 foundConfigNodes.removeAll(typeAndName);
211 logger.debug("Found {} config nodes {} without specified namespace in {}", foundConfigNodes.size(), name,
214 List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
215 XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
216 foundWithoutNamespaceNodes.removeAll(typeAndName);
217 if (!foundWithoutNamespaceNodes.isEmpty()){
218 throw new NetconfDocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
219 foundWithoutNamespaceNodes),
220 NetconfDocumentedException.ErrorType.application,
221 NetconfDocumentedException.ErrorTag.invalid_value,
222 NetconfDocumentedException.ErrorSeverity.error);
226 recognisedChildren.addAll(foundConfigNodes);
227 return foundConfigNodes;
230 private static Map<String, AttributeIfc> reverseMap(Map<String, AttributeIfc> yangNameToAttr) {
231 Map<String, AttributeIfc> reversednameToAtr = Maps.newHashMap();
233 for (Entry<String, AttributeIfc> entry : yangNameToAttr.entrySet()) {
234 reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue());
237 return reversednameToAtr;