7948bb6f42fd0876975fa70ee33cb0eee4d6cf25
[controller.git] / opendaylight / netconf / config-netconf-connector / src / main / java / org / opendaylight / controller / netconf / confignetconfconnector / operations / editconfig / EditConfig.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.operations.editconfig;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.Maps;
15 import com.google.common.collect.Multimap;
16 import java.util.Date;
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.Set;
20 import javax.management.InstanceNotFoundException;
21 import javax.management.ObjectName;
22 import org.opendaylight.controller.config.api.ValidationException;
23 import org.opendaylight.controller.config.util.BeanReader;
24 import org.opendaylight.controller.config.util.ConfigRegistryClient;
25 import org.opendaylight.controller.config.util.ConfigTransactionClient;
26 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
27 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
29 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
30 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
31 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
32 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
33 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
34 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfigElementResolved;
35 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleConfig;
36 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementDefinition;
37 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementResolved;
38 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
39 import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
40 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser.EditConfigExecution;
41 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
42 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
43 import org.opendaylight.controller.netconf.util.xml.XmlElement;
44 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
45 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51
52 public class EditConfig extends AbstractConfigNetconfOperation {
53
54     private static final Logger LOG = LoggerFactory.getLogger(EditConfig.class);
55
56     private final YangStoreContext yangStoreSnapshot;
57
58     private final TransactionProvider transactionProvider;
59     private EditConfigXmlParser editConfigXmlParser;
60
61     public EditConfig(YangStoreContext yangStoreSnapshot, TransactionProvider transactionProvider,
62             ConfigRegistryClient configRegistryClient, String netconfSessionIdForReporting) {
63         super(configRegistryClient, netconfSessionIdForReporting);
64         this.yangStoreSnapshot = yangStoreSnapshot;
65         this.transactionProvider = transactionProvider;
66         this.editConfigXmlParser = new EditConfigXmlParser();
67     }
68
69     @VisibleForTesting
70     Element getResponseInternal(final Document document,
71             final EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
72
73         if (editConfigExecution.shouldTest()) {
74             executeTests(getConfigRegistryClient(), editConfigExecution);
75         }
76
77         if (editConfigExecution.shouldSet()) {
78             executeSet(getConfigRegistryClient(), editConfigExecution);
79         }
80
81         LOG.trace("Operation {} successful", EditConfigXmlParser.EDIT_CONFIG);
82
83         return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
84     }
85
86     private void executeSet(ConfigRegistryClient configRegistryClient,
87             EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
88         set(configRegistryClient, editConfigExecution);
89         LOG.debug("Set phase for {} operation successful", EditConfigXmlParser.EDIT_CONFIG);
90     }
91
92     private void executeTests(ConfigRegistryClient configRegistryClient,
93             EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
94         try {
95             test(configRegistryClient, editConfigExecution, editConfigExecution.getDefaultStrategy());
96         } catch (final ValidationException e) {
97             LOG.warn("Test phase for {} failed", EditConfigXmlParser.EDIT_CONFIG, e);
98             final Map<String, String> errorInfo = new HashMap<>();
99             errorInfo.put(ErrorTag.operation_failed.name(), e.getMessage());
100             throw new NetconfDocumentedException("Test phase: " + e.getMessage(), e, ErrorType.application,
101                     ErrorTag.operation_failed, ErrorSeverity.error, errorInfo);
102         }
103         LOG.debug("Test phase for {} operation successful", EditConfigXmlParser.EDIT_CONFIG);
104     }
105
106     private void test(ConfigRegistryClient configRegistryClient, EditConfigExecution execution,
107             EditStrategyType editStrategyType) throws ValidationException, NetconfDocumentedException {
108         ObjectName taON = transactionProvider.getTestTransaction();
109         try {
110             // default strategy = replace wipes config
111             if (editStrategyType == EditStrategyType.replace) {
112                 transactionProvider.wipeTestTransaction(taON);
113             }
114
115             ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
116
117             handleMisssingInstancesOnTransaction(ta, execution);
118             setServicesOnTransaction(ta, execution);
119             setOnTransaction(ta, execution);
120             transactionProvider.validateTestTransaction(taON);
121         } finally {
122             transactionProvider.abortTestTransaction(taON);
123         }
124     }
125
126     private void set(ConfigRegistryClient configRegistryClient,
127             EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
128         ObjectName taON = transactionProvider.getOrCreateTransaction();
129
130         // default strategy = replace wipes config
131         if (editConfigExecution.getDefaultStrategy() == EditStrategyType.replace) {
132             transactionProvider.wipeTransaction();
133         }
134
135         ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
136
137         handleMisssingInstancesOnTransaction(ta, editConfigExecution);
138         setServicesOnTransaction(ta, editConfigExecution);
139         setOnTransaction(ta, editConfigExecution);
140     }
141
142     private void setServicesOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) throws NetconfDocumentedException {
143
144         Services services = execution.getServices();
145
146         Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = services
147                 .getNamespaceToServiceNameToRefNameToInstance();
148
149         for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance.entrySet()) {
150             for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry : namespaceToServiceToRefEntry.getValue().entrySet()) {
151
152                 String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
153                 Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
154
155                 for (Map.Entry<String, Services.ServiceInstance> refNameToServiceEntry : refNameToInstance.entrySet()) {
156                     ObjectName on = refNameToServiceEntry.getValue().getObjectName(ta.getTransactionName());
157                     try {
158                         ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(), on);
159                         LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
160                                 on, refNameToServiceEntry.getKey(), saved);
161                     } catch (InstanceNotFoundException e) {
162                         throw new NetconfDocumentedException(String.format("Unable to save ref name " + refNameToServiceEntry.getKey() + " for instance " + on, e),
163                                 ErrorType.application,
164                                 ErrorTag.operation_failed,
165                                 ErrorSeverity.error);
166                     }
167                 }
168             }
169         }
170     }
171
172     private String getQname(ConfigTransactionClient ta, String namespace, String serviceName) {
173         return ta.getServiceInterfaceName(namespace, serviceName);
174     }
175
176     private void setOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) throws NetconfDocumentedException {
177
178         for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta).values()) {
179
180             for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
181                 String moduleName = moduleToResolved.getKey();
182
183                 ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
184                 String instanceName = moduleElementResolved.getInstanceName();
185
186                 InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
187                 EditConfigStrategy strategy = ice.getEditStrategy();
188                 strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta, execution.getServiceRegistryWrapper(ta));
189             }
190         }
191     }
192
193     private void handleMisssingInstancesOnTransaction(ConfigTransactionClient ta,
194             EditConfigExecution execution) throws NetconfDocumentedException {
195
196         for (Multimap<String,ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta).values()) {
197             for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
198                 String moduleName = moduleToResolved.getKey();
199
200                 ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
201
202                 EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
203                 strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta, execution.getServiceRegistryWrapper(ta));
204             }
205         }
206     }
207
208     public static Config getConfigMapping(ConfigRegistryClient configRegistryClient, YangStoreContext yangStoreSnapshot) {
209         Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(configRegistryClient,
210                 yangStoreSnapshot.getModuleMXBeanEntryMap());
211         Map<String, Map<Date, IdentityMapping>> identitiesMap = transformIdentities(yangStoreSnapshot.getModules());
212         return new Config(factories, identitiesMap, yangStoreSnapshot.getEnumResolver());
213     }
214
215
216     public static class IdentityMapping {
217         private final Map<String, IdentitySchemaNode> identityNameToSchemaNode;
218
219         IdentityMapping() {
220             this.identityNameToSchemaNode = Maps.newHashMap();
221         }
222
223         void addIdSchemaNode(IdentitySchemaNode node) {
224             String name = node.getQName().getLocalName();
225             Preconditions.checkState(!identityNameToSchemaNode.containsKey(name));
226             identityNameToSchemaNode.put(name, node);
227         }
228
229         public boolean containsIdName(String idName) {
230             return identityNameToSchemaNode.containsKey(idName);
231         }
232
233     }
234
235     private static Map<String, Map<Date, IdentityMapping>> transformIdentities(Set<Module> modules) {
236         Map<String, Map<Date, IdentityMapping>> mappedIds = Maps.newHashMap();
237         for (Module module : modules) {
238             String namespace = module.getNamespace().toString();
239             Map<Date, IdentityMapping> revisionsByNamespace= mappedIds.get(namespace);
240             if(revisionsByNamespace == null) {
241                 revisionsByNamespace = Maps.newHashMap();
242                 mappedIds.put(namespace, revisionsByNamespace);
243             }
244
245             Date revision = module.getRevision();
246
247             IdentityMapping identityMapping = revisionsByNamespace.get(revision);
248             if(identityMapping == null) {
249                 identityMapping = new IdentityMapping();
250                 revisionsByNamespace.put(revision, identityMapping);
251             }
252
253             for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
254                 identityMapping.addIdSchemaNode(identitySchemaNode);
255             }
256
257         }
258
259         return mappedIds;
260     }
261
262     public static Map<String/* Namespace from yang file */,
263         Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs (
264             final BeanReader configRegistryClient, Map<String/* Namespace from yang file */,
265             Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
266
267         Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = Maps.newHashMap();
268
269         for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mBeanEntries.entrySet()) {
270             for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
271                 String moduleName = moduleNameToMbe.getKey();
272                 ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
273
274                 ModuleConfig moduleConfig = new ModuleConfig(moduleName,
275                         new InstanceConfig(configRegistryClient,moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
276
277                 Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig.get(namespaceToModuleToMbe.getKey());
278                 if(moduleNameToModuleConfig == null) {
279                     moduleNameToModuleConfig = Maps.newHashMap();
280                     namespaceToModuleNameToModuleConfig.put(namespaceToModuleToMbe.getKey(), moduleNameToModuleConfig);
281                 }
282
283                 moduleNameToModuleConfig.put(moduleName, moduleConfig);
284             }
285         }
286
287         return namespaceToModuleNameToModuleConfig;
288     }
289
290     @Override
291     protected String getOperationName() {
292         return EditConfigXmlParser.EDIT_CONFIG;
293     }
294
295     @Override
296     protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
297         EditConfigXmlParser.EditConfigExecution editConfigExecution;
298         Config cfg = getConfigMapping(getConfigRegistryClient(), yangStoreSnapshot);
299         editConfigExecution = editConfigXmlParser.fromXml(xml, cfg);
300
301         Element responseInternal;
302         responseInternal = getResponseInternal(document, editConfigExecution);
303         return responseInternal;
304     }
305
306 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.