2 * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.config.facade.xml;
11 import com.google.common.base.Optional;
12 import com.google.common.collect.Multimap;
14 import java.io.Closeable;
15 import java.util.Date;
16 import java.util.HashMap;
17 import java.util.List;
21 import javax.management.InstanceNotFoundException;
22 import javax.management.ObjectName;
24 import org.opendaylight.controller.config.api.ConflictingVersionException;
25 import org.opendaylight.controller.config.api.ValidationException;
26 import org.opendaylight.controller.config.api.jmx.CommitStatus;
27 import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
28 import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
29 import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfig;
30 import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfigElementResolved;
31 import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
32 import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
33 import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
34 import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
35 import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
36 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreContext;
37 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
38 import org.opendaylight.controller.config.facade.xml.runtime.InstanceRuntime;
39 import org.opendaylight.controller.config.facade.xml.runtime.ModuleRuntime;
40 import org.opendaylight.controller.config.facade.xml.runtime.Runtime;
41 import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
42 import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
43 import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
44 import org.opendaylight.controller.config.util.BeanReader;
45 import org.opendaylight.controller.config.util.ConfigRegistryClient;
46 import org.opendaylight.controller.config.util.ConfigTransactionClient;
47 import org.opendaylight.controller.config.util.xml.DocumentedException;
48 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
49 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
50 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
51 import org.opendaylight.controller.config.util.xml.XmlElement;
52 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
53 import org.opendaylight.controller.config.util.xml.XmlUtil;
54 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
55 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
56 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.Module;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.w3c.dom.Document;
61 import org.w3c.dom.Element;
64 * Config subsystem facade for xml format.
67 * TODO extract generic interface for config subsystem facades
69 public class ConfigSubsystemFacade implements Closeable {
71 private static final Logger LOG = LoggerFactory.getLogger(ConfigSubsystemFacade.class);
72 private final YangStoreService yangStoreService;
73 private final TransactionProvider transactionProvider;
74 private final ConfigRegistryClient configRegistryClient;
75 private final ConfigRegistryClient configRegistryClientNoNotifications;
76 private final RpcFacade rpcFacade;
78 public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient,
79 final ConfigRegistryClient configRegistryClientNoNotifications,
80 final YangStoreService yangStoreService,
82 this.configRegistryClient = configRegistryClient;
83 this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
84 this.yangStoreService = yangStoreService;
85 this.transactionProvider = new TransactionProvider(configRegistryClient, id);
86 rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
89 public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient,
90 final ConfigRegistryClient configRegistryClientNoNotifications,
91 final YangStoreService yangStoreService,
92 final TransactionProvider txProvider) {
93 this.configRegistryClient = configRegistryClient;
94 this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
95 this.yangStoreService = yangStoreService;
96 this.transactionProvider = txProvider;
97 rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
100 public Element getConfiguration(final Document document, final Datastore source,
101 final Optional<String> maybeNamespace) {
103 final ConfigTransactionClient registryClient;
104 // Read current state from a transaction, if running is source, then start new
105 // transaction just for reading
106 // in case of candidate, get current transaction representing candidate
107 if (source == Datastore.running) {
108 final ObjectName readTx = transactionProvider.getOrCreateReadTransaction();
109 registryClient = configRegistryClient.getConfigTransactionClient(readTx);
111 registryClient = configRegistryClient
112 .getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
116 Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY,
117 Optional.<String>absent());
118 final Set<ObjectName> instances = Datastore.getInstanceQueryStrategy(source, this.transactionProvider)
119 .queryInstances(configRegistryClient);
121 final Config configMapping = new Config(
122 transformMbeToModuleConfigs(yangStoreService.getModuleMXBeanEntryMap()),
123 yangStoreService.getEnumResolver());
125 ServiceRegistryWrapper serviceTracker = new ServiceRegistryWrapper(registryClient);
126 dataElement = configMapping.toXml(instances, maybeNamespace, document, dataElement, serviceTracker);
130 if (source == Datastore.running) {
131 transactionProvider.closeReadTransaction();
136 public void executeConfigExecution(final ConfigExecution configExecution)
137 throws DocumentedException, ValidationException {
138 if (configExecution.shouldTest()) {
139 executeTests(configExecution);
142 if (configExecution.shouldSet()) {
143 executeSet(configExecution);
147 public CommitStatus commitTransaction()
148 throws DocumentedException, ValidationException, ConflictingVersionException {
149 final CommitStatus status = this.transactionProvider.commitTransaction();
150 LOG.trace("Transaction committed successfully: {}", status);
154 public CommitStatus commitSilentTransaction()
155 throws DocumentedException, ValidationException, ConflictingVersionException {
156 final CommitStatus status = this.transactionProvider.commitTransaction(configRegistryClientNoNotifications);
157 LOG.trace("Transaction committed successfully: {}", status);
161 private void executeSet(final ConfigExecution configExecution) throws DocumentedException {
162 set(configExecution);
163 LOG.debug("Set phase for {} operation successful, element: ", configExecution.getDefaultStrategy(),
164 configExecution.getConfigElement());
167 private void executeTests(final ConfigExecution configExecution) throws DocumentedException, ValidationException {
168 test(configExecution, configExecution.getDefaultStrategy());
169 LOG.debug("Test phase for {} operation successful, element: ", configExecution.getDefaultStrategy(),
170 configExecution.getConfigElement());
173 private void test(final ConfigExecution execution, final EditStrategyType editStrategyType)
174 throws ValidationException, DocumentedException {
175 ObjectName taON = transactionProvider.getTestTransaction();
177 // default strategy = replace wipes config
178 if (editStrategyType == EditStrategyType.replace) {
179 transactionProvider.wipeTestTransaction(taON);
182 ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
184 handleMisssingInstancesOnTransaction(ta, execution);
185 setServicesOnTransaction(ta, execution);
186 setOnTransaction(ta, execution);
187 transactionProvider.validateTestTransaction(taON);
189 transactionProvider.abortTestTransaction(taON);
193 private void set(final ConfigExecution configExecution) throws DocumentedException {
194 ObjectName taON = transactionProvider.getOrCreateTransaction();
196 // default strategy = replace wipes config
197 if (configExecution.getDefaultStrategy() == EditStrategyType.replace) {
198 transactionProvider.wipeTransaction();
201 ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
203 handleMisssingInstancesOnTransaction(ta, configExecution);
204 setServicesOnTransaction(ta, configExecution);
205 setOnTransaction(ta, configExecution);
208 private void setServicesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
209 throws DocumentedException {
210 Services services = execution.getServices();
212 Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance =
213 services.getNamespaceToServiceNameToRefNameToInstance();
215 for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>>
216 namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance
218 for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry
219 : namespaceToServiceToRefEntry.getValue().entrySet()) {
220 String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
221 Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
223 for (Map.Entry<String, Services.ServiceInstance> refNameToServiceEntry : refNameToInstance.entrySet()) {
224 ObjectName on = refNameToServiceEntry.getValue().getObjectName(ta.getTransactionName());
226 if (Services.ServiceInstance.EMPTY_SERVICE_INSTANCE == refNameToServiceEntry.getValue()) {
227 ta.removeServiceReference(qnameOfService, refNameToServiceEntry.getKey());
228 LOG.debug("Removing service {} with name {}", qnameOfService,
229 refNameToServiceEntry.getKey());
231 ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(),
233 LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
234 on, refNameToServiceEntry.getKey(), saved);
236 } catch (final InstanceNotFoundException e) {
237 throw new DocumentedException(
238 String.format("Unable to edit ref name " + refNameToServiceEntry.getKey()
239 + " for instance " + on, e),
240 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
247 private String getQname(final ConfigTransactionClient ta, final String namespace, final String serviceName) {
248 return ta.getServiceInterfaceName(namespace, serviceName);
251 private void setOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
252 throws DocumentedException {
254 for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta)
257 for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
258 String moduleName = moduleToResolved.getKey();
260 ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
261 String instanceName = moduleElementResolved.getInstanceName();
263 InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
264 EditConfigStrategy strategy = ice.getEditStrategy();
265 strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta,
266 execution.getServiceRegistryWrapper(ta));
271 private void handleMisssingInstancesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
272 throws DocumentedException {
274 for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta)
276 for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
277 String moduleName = moduleToResolved.getKey();
279 ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
281 EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
282 strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta,
283 execution.getServiceRegistryWrapper(ta));
288 public Config getConfigMapping() {
289 final YangStoreContext snapshot = yangStoreService.getCurrentSnapshot();
290 Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(
291 snapshot.getModuleMXBeanEntryMap());
292 Map<String, Map<Date, IdentityMapping>> identitiesMap = transformIdentities(snapshot.getModules());
293 return new Config(factories, identitiesMap, snapshot.getEnumResolver());
296 private static Map<String, Map<Date, IdentityMapping>> transformIdentities(final Set<Module> modules) {
297 Map<String, Map<Date, IdentityMapping>> mappedIds = new HashMap<>();
298 for (Module module : modules) {
299 String namespace = module.getNamespace().toString();
300 Map<Date, IdentityMapping> revisionsByNamespace = mappedIds.computeIfAbsent(namespace,
301 k -> new HashMap<>());
303 Date revision = module.getRevision();
305 IdentityMapping identityMapping = revisionsByNamespace.computeIfAbsent(revision,
306 k -> new IdentityMapping());
308 for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
309 identityMapping.addIdSchemaNode(identitySchemaNode);
317 public Map<String/* Namespace from yang file */,
318 Map<String /* Name of module entry from yang file */,
319 ModuleConfig>> transformMbeToModuleConfigs(
320 final Map<String/* Namespace from yang file */,
321 Map<String /* Name of module entry from yang file */,
322 ModuleMXBeanEntry>> mbeanentries) {
323 return transformMbeToModuleConfigs(configRegistryClient, mbeanentries);
326 public Map<String/* Namespace from yang file */,
327 Map<String /* Name of module entry from yang file */,
328 ModuleConfig>> transformMbeToModuleConfigs(
329 final BeanReader reader,
330 final Map<String/* Namespace from yang file */,
331 Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mbeanentries) {
332 Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = new HashMap<>();
334 for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mbeanentries.entrySet()) {
335 for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
336 String moduleName = moduleNameToMbe.getKey();
337 ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
339 ModuleConfig moduleConfig = new ModuleConfig(moduleName, new InstanceConfig(reader,
340 moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
342 Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig
343 .computeIfAbsent(namespaceToModuleToMbe.getKey(), k -> new HashMap<>());
345 moduleNameToModuleConfig.put(moduleName, moduleConfig);
349 return namespaceToModuleNameToModuleConfig;
352 public ConfigExecution getConfigExecution(final Config configMapping, final Element xmlToBePersisted)
353 throws DocumentedException {
354 return new ConfigExecution(configMapping, XmlElement.fromDomElement(xmlToBePersisted), TestOption.testThenSet,
355 EditStrategyType.getDefaultStrategy());
358 private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(
359 final ConfigRegistryClient client,
360 final Map<String, Map<String, ModuleMXBeanEntry>> mbeanentries) {
361 Map<String, Map<String, ModuleRuntime>> retVal = new HashMap<>();
363 for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mbeanentries.entrySet()) {
365 Map<String, ModuleRuntime> innerMap = new HashMap<>();
366 Map<String, ModuleMXBeanEntry> entriesFromNamespace = namespaceToModuleEntry.getValue();
367 for (Map.Entry<String, ModuleMXBeanEntry> moduleToMXEntry : entriesFromNamespace.entrySet()) {
369 ModuleMXBeanEntry mbe = moduleToMXEntry.getValue();
371 Map<RuntimeBeanEntry, InstanceConfig> cache = new HashMap<>();
372 RuntimeBeanEntry root = null;
373 for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
374 cache.put(rbe, new InstanceConfig(client, rbe.getYangPropertiesToTypesMap(),
375 mbe.getNullableDummyContainerName()));
385 InstanceRuntime rootInstanceRuntime = createInstanceRuntime(root, cache);
386 ModuleRuntime moduleRuntime = new ModuleRuntime(rootInstanceRuntime);
387 innerMap.put(moduleToMXEntry.getKey(), moduleRuntime);
390 retVal.put(namespaceToModuleEntry.getKey(), innerMap);
395 private InstanceRuntime createInstanceRuntime(final RuntimeBeanEntry root,
396 final Map<RuntimeBeanEntry, InstanceConfig> cache) {
397 Map<String, InstanceRuntime> children = new HashMap<>();
398 for (RuntimeBeanEntry child : root.getChildren()) {
399 children.put(child.getJavaNamePrefix(), createInstanceRuntime(child, cache));
402 return new InstanceRuntime(cache.get(root), children, createJmxToYangMap(root.getChildren()));
405 private Map<String, String> createJmxToYangMap(final List<RuntimeBeanEntry> children) {
406 Map<String, String> jmxToYangNamesForChildRbe = new HashMap<>();
407 for (RuntimeBeanEntry rbe : children) {
408 jmxToYangNamesForChildRbe.put(rbe.getJavaNamePrefix(), rbe.getYangName());
410 return jmxToYangNamesForChildRbe;
413 public Element get(final Document document) throws DocumentedException {
414 final ObjectName testTransaction = transactionProvider.getOrCreateReadTransaction();
415 final ConfigTransactionClient txClient = configRegistryClient.getConfigTransactionClient(testTransaction);
418 // Runtime beans are not parts of transactions and have to be queried against
419 // the central registry
420 final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
422 final Set<ObjectName> configBeans = Datastore
423 .getInstanceQueryStrategy(Datastore.running, transactionProvider)
424 .queryInstances(configRegistryClient);
426 final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(configRegistryClient,
427 yangStoreService.getModuleMXBeanEntryMap());
429 final YangStoreContext yangStoreSnapshot = yangStoreService.getCurrentSnapshot();
430 final Map<String, Map<String, ModuleConfig>> moduleConfigs = transformMbeToModuleConfigs(txClient,
431 yangStoreSnapshot.getModuleMXBeanEntryMap());
433 final org.opendaylight.controller.config.facade.xml.runtime.Runtime runtime = new Runtime(moduleRuntimes,
436 return runtime.toXml(runtimeBeans, configBeans, document, yangStoreSnapshot.getEnumResolver());
438 transactionProvider.closeReadTransaction();
442 public void abortConfiguration() {
443 if (transactionProvider.getTransaction().isPresent()) {
444 this.transactionProvider.abortTransaction();
448 public void validateConfiguration() throws ValidationException {
449 transactionProvider.validateTransaction();
453 public void close() {
454 transactionProvider.close();
457 public RpcFacade getRpcFacade() {