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