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;
14 import java.util.Date;
15 import java.util.List;
17 import java.util.Map.Entry;
18 import javax.management.ObjectName;
19 import javax.management.openmbean.OpenType;
20 import org.opendaylight.controller.config.util.ConfigRegistryClient;
21 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
22 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
23 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
24 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
25 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
26 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
27 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
28 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
29 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
30 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.ObjectResolver;
31 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.AttributeWritingStrategy;
32 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
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.XmlNetconfConstants;
37 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.w3c.dom.Document;
41 import org.w3c.dom.Element;
43 public final class InstanceConfig {
44 private static final Logger logger = LoggerFactory.getLogger(InstanceConfig.class);
46 private final Map<String, AttributeIfc> yangToAttrConfig;
47 private final String nullableDummyContainerName;
48 private final Map<String, AttributeIfc> jmxToAttrConfig;
49 private final ConfigRegistryClient configRegistryClient;
51 public InstanceConfig(ConfigRegistryClient configRegistryClient, Map<String, AttributeIfc> yangNamesToAttributes,
52 String nullableDummyContainerName) {
54 this.yangToAttrConfig = yangNamesToAttributes;
55 this.nullableDummyContainerName = nullableDummyContainerName;
56 this.jmxToAttrConfig = reverseMap(yangNamesToAttributes);
57 this.configRegistryClient = configRegistryClient;
60 private Map<String, Object> getMappedConfiguration(ObjectName on) {
62 // TODO make field, mappingStrategies can be instantiated only once
63 Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> mappingStrategies = new ObjectMapper()
64 .prepareMapping(jmxToAttrConfig);
66 Map<String, Object> toXml = Maps.newHashMap();
68 for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
69 // Skip children runtime beans as they are mapped by InstanceRuntime
70 if (configDefEntry.getValue() instanceof RuntimeBeanEntry){
73 Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
75 AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
76 .get(configDefEntry.getKey());
77 Optional<?> a = attributeMappingStrategy.mapAttribute(value);
81 toXml.put(configDefEntry.getValue().getAttributeYangName(), a.get());
82 } catch (Exception e) {
83 throw new IllegalStateException("Unable to map value " + value + " to attribute "
84 + configDefEntry.getKey(), e);
90 public Element toXml(ObjectName on, String namespace, Document document, Element rootElement) {
91 Map<String, AttributeWritingStrategy> strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document);
92 Map<String, Object> mappedConfig = getMappedConfiguration(on);
93 Element parentElement;
94 if (nullableDummyContainerName != null) {
95 Element dummyElement = XmlUtil.createElement(document, nullableDummyContainerName, Optional.of(namespace));
96 rootElement.appendChild(dummyElement);
97 parentElement = dummyElement;
99 parentElement = rootElement;
101 for (Entry<String, ?> mappingEntry : mappedConfig.entrySet()) {
103 strats.get(mappingEntry.getKey()).writeElement(parentElement, namespace, mappingEntry.getValue());
104 } catch (Exception e) {
105 throw new IllegalStateException("Unable to write value " + mappingEntry.getValue() + " for attribute "
106 + mappingEntry.getValue(), e);
112 private void resolveConfiguration(InstanceConfigElementResolved mappedConfig, ServiceRegistryWrapper depTracker) {
114 // TODO make field, resolvingStrategies can be instantiated only once
115 Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(
116 depTracker).prepareResolving(yangToAttrConfig);
118 for (Entry<String, AttributeConfigElement> configDefEntry : mappedConfig.getConfiguration().entrySet()) {
119 AttributeConfigElement value = configDefEntry.getValue();
120 String attributeName = configDefEntry.getKey();
122 AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
124 logger.trace("Trying to set value {} of attribute {} with {}", value, attributeName, attributeResolvingStrategy);
126 value.resolveValue(attributeResolvingStrategy, attributeName);
128 yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
129 } catch (Exception e) {
130 throw new IllegalStateException("Unable to resolve value " + value
131 + " to attribute " + attributeName, e);
136 public InstanceConfigElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper services, String moduleNamespace,
137 EditStrategyType defaultStrategy,
138 Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) throws NetconfDocumentedException {
139 Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
141 Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
142 List<XmlElement> recognisedChildren = Lists.newArrayList();
144 XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
145 XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
146 List<XmlElement> typeAndNameElements = Lists.newArrayList(typeElement, nameElement);
148 // if dummy container was defined in yang, set moduleElement to its content
149 if (nullableDummyContainerName != null) {
150 int size = moduleElement.getChildElements().size();
151 int expectedChildNodes = 1 + typeAndNameElements.size();
152 if (size > expectedChildNodes) {
153 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
154 nameElement.getTextContent() + " - Expected " + expectedChildNodes +" child nodes, " +
155 "one of them with name " + nullableDummyContainerName +
156 ", got " + size + " elements.");
158 if (size == expectedChildNodes) {
160 moduleElement = moduleElement.getOnlyChildElement(nullableDummyContainerName, moduleNamespace);
161 } catch (NetconfDocumentedException e) {
162 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
163 nameElement.getTextContent() + " - Expected child node with name " + nullableDummyContainerName +
164 "." + e.getMessage());
166 } // else 2 elements, no need to descend
169 for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
170 List<XmlElement> configNodes = getConfigNodes(moduleElement, moduleNamespace, readStratEntry.getKey(),
171 recognisedChildren, typeAndNameElements);
172 AttributeConfigElement readElement = readStratEntry.getValue().readElement(configNodes);
173 retVal.put(readStratEntry.getKey(), readElement);
176 recognisedChildren.addAll(typeAndNameElements);
178 moduleElement.checkUnrecognisedElements(recognisedChildren);
179 } catch (NetconfDocumentedException e) {
180 throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
181 nameElement.getTextContent() + " - " +
182 e.getMessage(), e.getErrorType(), e.getErrorTag(),e.getErrorSeverity(),e.getErrorInfo());
184 // TODO: add check for conflicts between global and local edit strategy
185 String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
186 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
188 InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("") ? new InstanceConfigElementResolved(
189 retVal, defaultStrategy) : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
191 resolveConfiguration(instanceConfigElementResolved, services);
192 return instanceConfigElementResolved;
195 private List<XmlElement> getConfigNodes(XmlElement moduleElement, String moduleNamespace, String name,
196 List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws NetconfDocumentedException {
197 List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
198 if (foundConfigNodes.isEmpty()) {
199 logger.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
200 logger.debug("Trying lookup of config nodes without specified namespace");
201 foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name,
202 XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
203 // In case module type or name element is not present in config it
204 // would be matched with config type or name
205 // We need to remove config type and name from available module
207 foundConfigNodes.removeAll(typeAndName);
208 logger.debug("Found {} config nodes {} without specified namespace in {}", foundConfigNodes.size(), name,
211 List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
212 XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
213 foundWithoutNamespaceNodes.removeAll(typeAndName);
214 if (!foundWithoutNamespaceNodes.isEmpty()){
215 throw new NetconfDocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
216 foundWithoutNamespaceNodes),
217 NetconfDocumentedException.ErrorType.application,
218 NetconfDocumentedException.ErrorTag.invalid_value,
219 NetconfDocumentedException.ErrorSeverity.error);
223 recognisedChildren.addAll(foundConfigNodes);
224 return foundConfigNodes;
227 private static Map<String, AttributeIfc> reverseMap(Map<String, AttributeIfc> yangNameToAttr) {
228 Map<String, AttributeIfc> reversednameToAtr = Maps.newHashMap();
230 for (Entry<String, AttributeIfc> entry : yangNameToAttr.entrySet()) {
231 reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue());
234 return reversednameToAtr;