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