Merge "Bug 451 - Fix netconf exception handling"
[controller.git] / opendaylight / netconf / config-netconf-connector / src / main / java / org / opendaylight / controller / netconf / confignetconfconnector / mapping / config / InstanceConfig.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.collect.Lists;
13 import com.google.common.collect.Maps;
14 import com.google.common.collect.Multimap;
15 import org.opendaylight.controller.config.util.ConfigRegistryClient;
16 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
17 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
18 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
19 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
20 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
21 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
22 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
23 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
24 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
25 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.ObjectResolver;
26 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.AttributeWritingStrategy;
27 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
28 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
29 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
30 import org.opendaylight.controller.netconf.util.xml.XmlElement;
31 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.w3c.dom.Document;
35 import org.w3c.dom.Element;
36
37 import javax.management.ObjectName;
38 import javax.management.openmbean.OpenType;
39 import java.util.Date;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Map.Entry;
43
44 public final class InstanceConfig {
45     private static final Logger logger = LoggerFactory.getLogger(InstanceConfig.class);
46
47     private final Map<String, AttributeIfc> yangToAttrConfig;
48     private final Map<String, AttributeIfc> jmxToAttrConfig;
49     private final ConfigRegistryClient configRegistryClient;
50
51     public InstanceConfig(ConfigRegistryClient configRegistryClient, Map<String, AttributeIfc> yangNamesToAttributes) {
52         this.yangToAttrConfig = yangNamesToAttributes;
53         this.jmxToAttrConfig = reverseMap(yangNamesToAttributes);
54         this.configRegistryClient = configRegistryClient;
55     }
56
57     private Map<String, Object> getMappedConfiguration(ObjectName on, ServiceRegistryWrapper depTracker) {
58
59         // TODO make field, mappingStrategies can be instantiated only once
60         Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> mappingStrategies = new ObjectMapper(depTracker)
61                 .prepareMapping(jmxToAttrConfig);
62
63         Map<String, Object> toXml = Maps.newHashMap();
64
65         for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
66
67             // Skip children runtime beans as they are mapped by InstanceRuntime
68             if (configDefEntry.getValue() instanceof RuntimeBeanEntry)
69                 continue;
70
71             Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
72             try {
73                 AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
74                         .get(configDefEntry.getKey());
75                 Optional<?> a = attributeMappingStrategy.mapAttribute(value);
76                 if (a.isPresent() == false)
77                     continue;
78
79                 toXml.put(configDefEntry.getValue().getAttributeYangName(), a.get());
80             } catch (Exception e) {
81                 throw new IllegalStateException("Unable to map value " + value + " to attribute "
82                         + configDefEntry.getKey(), e);
83             }
84         }
85
86         return toXml;
87     }
88
89     public Element toXml(ObjectName on, ServiceRegistryWrapper depTracker, String namespace, Document document, Element rootElement) {
90
91         Element cfgElement = rootElement;
92
93         Map<String, AttributeWritingStrategy> strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document);
94
95         Map<String, Object> mappedConfig = getMappedConfiguration(on, depTracker);
96
97         for (Entry<String, ?> mappingEntry : mappedConfig.entrySet()) {
98             try {
99                 strats.get(mappingEntry.getKey()).writeElement(cfgElement, namespace, mappingEntry.getValue());
100             } catch (Exception e) {
101                 throw new IllegalStateException("Unable to write value " + mappingEntry.getValue() + " for attribute "
102                         + mappingEntry.getValue(), e);
103             }
104         }
105
106         return cfgElement;
107     }
108
109     private void resolveConfiguration(InstanceConfigElementResolved mappedConfig, ServiceRegistryWrapper depTracker) {
110
111         // TODO make field, resolvingStrategies can be instantiated only once
112         Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(
113                 depTracker).prepareResolving(yangToAttrConfig);
114
115         for (Entry<String, AttributeConfigElement> configDefEntry : mappedConfig.getConfiguration().entrySet()) {
116             AttributeConfigElement value = configDefEntry.getValue();
117             String attributeName = configDefEntry.getKey();
118             try {
119                 AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
120                         .get(attributeName);
121                 logger.trace("Trying to set value {} of attribute {} with {}", value, attributeName, attributeResolvingStrategy);
122
123                 value.resolveValue(attributeResolvingStrategy, attributeName);
124                 value.setJmxName(
125                         yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
126             } catch (Exception e) {
127                 throw new IllegalStateException("Unable to resolve value " + value
128                         + " to attribute " + attributeName, e);
129             }
130         }
131     }
132
133     public InstanceConfigElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper services, String moduleNamespace,
134                                                  EditStrategyType defaultStrategy, Multimap<String, String> providedServices, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) throws NetconfDocumentedException {
135         Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
136
137         Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
138         List<XmlElement> recognisedChildren = Lists.newArrayList();
139
140         XmlElement type = null;
141         XmlElement name = null;
142         type = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
143         name = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
144         List<XmlElement> typeAndName = Lists.newArrayList(type, name);
145
146         for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
147             List<XmlElement> configNodes = getConfigNodes(moduleElement, moduleNamespace, readStratEntry.getKey(),
148                     recognisedChildren, typeAndName);
149             AttributeConfigElement readElement = readStratEntry.getValue().readElement(configNodes);
150             retVal.put(readStratEntry.getKey(), readElement);
151         }
152
153         recognisedChildren.addAll(typeAndName);
154         moduleElement.checkUnrecognisedElements(recognisedChildren);
155
156         // TODO: add check for conflicts between global and local edit strategy
157         String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
158                 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
159
160         InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("") ? new InstanceConfigElementResolved(
161                 retVal, defaultStrategy, providedServices) : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy, providedServices);
162
163         resolveConfiguration(instanceConfigElementResolved, services);
164         return instanceConfigElementResolved;
165     }
166
167     private List<XmlElement> getConfigNodes(XmlElement moduleElement, String moduleNamespace, String name,
168             List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws NetconfDocumentedException {
169         List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
170         if (foundConfigNodes.isEmpty()) {
171             logger.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
172             logger.debug("Trying lookup of config nodes without specified namespace");
173             foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name,
174                     XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
175             // In case module type or name element is not present in config it
176             // would be matched with config type or name
177             // We need to remove config type and name from available module
178             // config elements
179             foundConfigNodes.removeAll(typeAndName);
180             logger.debug("Found {} config nodes {} without specified namespace in {}", foundConfigNodes.size(), name,
181                     moduleElement);
182         } else {
183             List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
184                     XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
185             foundWithoutNamespaceNodes.removeAll(typeAndName);
186             if (!foundWithoutNamespaceNodes.isEmpty()){
187                 throw new NetconfDocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
188                         foundWithoutNamespaceNodes),
189                         NetconfDocumentedException.ErrorType.application,
190                         NetconfDocumentedException.ErrorTag.invalid_value,
191                         NetconfDocumentedException.ErrorSeverity.error);
192             }
193         }
194
195         recognisedChildren.addAll(foundConfigNodes);
196         return foundConfigNodes;
197     }
198
199     private static Map<String, AttributeIfc> reverseMap(Map<String, AttributeIfc> yangNameToAttr) {
200         Map<String, AttributeIfc> reversednameToAtr = Maps.newHashMap();
201
202         for (Entry<String, AttributeIfc> entry : yangNameToAttr.entrySet()) {
203             reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue());
204         }
205
206         return reversednameToAtr;
207     }
208
209 }