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

©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.