2 * Copyright (c) 2015 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.Maps;
13 import com.google.common.collect.Multimap;
14 import java.io.Closeable;
15 import java.util.Date;
16 import java.util.List;
19 import javax.management.InstanceNotFoundException;
20 import javax.management.ObjectName;
21 import org.opendaylight.controller.config.api.ConflictingVersionException;
22 import org.opendaylight.controller.config.api.ValidationException;
23 import org.opendaylight.controller.config.api.jmx.CommitStatus;
24 import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
25 import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
26 import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfig;
27 import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfigElementResolved;
28 import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
29 import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
30 import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
31 import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
32 import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
33 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreContext;
34 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
35 import org.opendaylight.controller.config.facade.xml.runtime.InstanceRuntime;
36 import org.opendaylight.controller.config.facade.xml.runtime.ModuleRuntime;
37 import org.opendaylight.controller.config.facade.xml.runtime.Runtime;
38 import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
39 import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
40 import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
41 import org.opendaylight.controller.config.util.BeanReader;
42 import org.opendaylight.controller.config.util.ConfigRegistryClient;
43 import org.opendaylight.controller.config.util.ConfigTransactionClient;
44 import org.opendaylight.controller.config.util.xml.DocumentedException;
45 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
46 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
47 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
48 import org.opendaylight.controller.config.util.xml.XmlElement;
49 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
50 import org.opendaylight.controller.config.util.xml.XmlUtil;
51 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
52 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
53 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.w3c.dom.Document;
58 import org.w3c.dom.Element;
61 * Config subsystem facade for xml format
63 * TODO extract generic interface for config subsystem facades
65 public class ConfigSubsystemFacade implements Closeable {
67 private static final Logger LOG = LoggerFactory.getLogger(ConfigSubsystemFacade.class);
68 private final YangStoreService yangStoreService;
69 private final TransactionProvider transactionProvider;
70 private final ConfigRegistryClient configRegistryClient;
71 private final ConfigRegistryClient configRegistryClientNoNotifications;
72 private final RpcFacade rpcFacade;
74 public ConfigSubsystemFacade(ConfigRegistryClient configRegistryClient, ConfigRegistryClient configRegistryClientNoNotifications, YangStoreService yangStoreService, String id) {
75 this.configRegistryClient = configRegistryClient;
76 this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
77 this.yangStoreService = yangStoreService;
78 this.transactionProvider = new TransactionProvider(configRegistryClient, id);
79 rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
82 public ConfigSubsystemFacade(ConfigRegistryClient configRegistryClient, ConfigRegistryClient configRegistryClientNoNotifications, YangStoreService yangStoreService, TransactionProvider txProvider) {
83 this.configRegistryClient = configRegistryClient;
84 this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
85 this.yangStoreService = yangStoreService;
86 this.transactionProvider = txProvider;
87 rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
90 public Element getConfiguration(final Document document, final Datastore source, final Optional<String> maybeNamespace) {
92 final ConfigTransactionClient registryClient;
93 // Read current state from a transaction, if running is source, then start new transaction just for reading
94 // in case of candidate, get current transaction representing candidate
95 if (source == Datastore.running) {
96 final ObjectName readTx = transactionProvider.getOrCreateReadTransaction();
97 registryClient = configRegistryClient.getConfigTransactionClient(readTx);
99 registryClient = configRegistryClient.getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
103 Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
104 final Set<ObjectName> instances = Datastore.getInstanceQueryStrategy(source, this.transactionProvider)
105 .queryInstances(configRegistryClient);
107 final Config configMapping =
108 new Config(transformMbeToModuleConfigs(yangStoreService.getModuleMXBeanEntryMap()), yangStoreService.getEnumResolver());
110 ServiceRegistryWrapper serviceTracker = new ServiceRegistryWrapper(registryClient);
111 dataElement = configMapping.toXml(instances, maybeNamespace, document, dataElement, serviceTracker);
115 if (source == Datastore.running) {
116 transactionProvider.closeReadTransaction();
121 public void executeConfigExecution(ConfigExecution configExecution) throws DocumentedException, ValidationException {
122 if (configExecution.shouldTest()) {
123 executeTests(configExecution);
126 if (configExecution.shouldSet()) {
127 executeSet(configExecution);
131 public CommitStatus commitTransaction() throws DocumentedException, ValidationException, ConflictingVersionException {
132 final CommitStatus status = this.transactionProvider.commitTransaction();
133 LOG.trace("Transaction committed successfully: {}", status);
137 public CommitStatus commitSilentTransaction() throws DocumentedException, ValidationException, ConflictingVersionException {
138 final CommitStatus status = this.transactionProvider.commitTransaction(configRegistryClientNoNotifications);
139 LOG.trace("Transaction committed successfully: {}", status);
143 private void executeSet(ConfigExecution configExecution) throws DocumentedException {
144 set(configExecution);
145 LOG.debug("Set phase for {} operation successful, element: ", configExecution.getDefaultStrategy(), configExecution.getConfigElement());
148 private void executeTests(ConfigExecution configExecution) throws DocumentedException, ValidationException {
149 test(configExecution, configExecution.getDefaultStrategy());
150 LOG.debug("Test phase for {} operation successful, element: ", configExecution.getDefaultStrategy(), configExecution.getConfigElement());
153 private void test(ConfigExecution execution, EditStrategyType editStrategyType) throws ValidationException, DocumentedException {
154 ObjectName taON = transactionProvider.getTestTransaction();
156 // default strategy = replace wipes config
157 if (editStrategyType == EditStrategyType.replace) {
158 transactionProvider.wipeTestTransaction(taON);
161 ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
163 handleMisssingInstancesOnTransaction(ta, execution);
164 setServicesOnTransaction(ta, execution);
165 setOnTransaction(ta, execution);
166 transactionProvider.validateTestTransaction(taON);
168 transactionProvider.abortTestTransaction(taON);
172 private void set(ConfigExecution ConfigExecution) throws DocumentedException {
173 ObjectName taON = transactionProvider.getOrCreateTransaction();
175 // default strategy = replace wipes config
176 if (ConfigExecution.getDefaultStrategy() == EditStrategyType.replace) {
177 transactionProvider.wipeTransaction();
180 ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
182 handleMisssingInstancesOnTransaction(ta, ConfigExecution);
183 setServicesOnTransaction(ta, ConfigExecution);
184 setOnTransaction(ta, ConfigExecution);
187 private void setServicesOnTransaction(ConfigTransactionClient ta, ConfigExecution execution) throws DocumentedException {
189 Services services = execution.getServices();
191 Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = services
192 .getNamespaceToServiceNameToRefNameToInstance();
194 for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance.entrySet()) {
195 for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry : namespaceToServiceToRefEntry.getValue().entrySet()) {
197 String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
198 Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
200 for (Map.Entry<String, Services.ServiceInstance> refNameToServiceEntry : refNameToInstance.entrySet()) {
201 ObjectName on = refNameToServiceEntry.getValue().getObjectName(ta.getTransactionName());
203 if (Services.ServiceInstance.EMPTY_SERVICE_INSTANCE == refNameToServiceEntry.getValue()) {
204 ta.removeServiceReference(qnameOfService, refNameToServiceEntry.getKey());
205 LOG.debug("Removing service {} with name {}", qnameOfService, refNameToServiceEntry.getKey());
207 ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(), on);
208 LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
209 on, refNameToServiceEntry.getKey(), saved);
211 } catch (InstanceNotFoundException e) {
212 throw new DocumentedException(String.format("Unable to edit ref name " + refNameToServiceEntry.getKey() + " for instance " + on, e),
213 ErrorType.application,
214 ErrorTag.operation_failed,
215 ErrorSeverity.error);
222 private String getQname(ConfigTransactionClient ta, String namespace, String serviceName) {
223 return ta.getServiceInterfaceName(namespace, serviceName);
226 private void setOnTransaction(ConfigTransactionClient ta, ConfigExecution execution) throws DocumentedException {
228 for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta).values()) {
230 for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
231 String moduleName = moduleToResolved.getKey();
233 ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
234 String instanceName = moduleElementResolved.getInstanceName();
236 InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
237 EditConfigStrategy strategy = ice.getEditStrategy();
238 strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta, execution.getServiceRegistryWrapper(ta));
243 private void handleMisssingInstancesOnTransaction(ConfigTransactionClient ta,
244 ConfigExecution execution) throws DocumentedException {
246 for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta).values()) {
247 for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
248 String moduleName = moduleToResolved.getKey();
250 ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
252 EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
253 strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta, execution.getServiceRegistryWrapper(ta));
258 public Config getConfigMapping() {
259 final YangStoreContext snapshot = yangStoreService.getCurrentSnapshot();
260 Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(snapshot.getModuleMXBeanEntryMap());
261 Map<String, Map<Date, IdentityMapping>> identitiesMap = transformIdentities(snapshot.getModules());
262 return new Config(factories, identitiesMap, snapshot.getEnumResolver());
265 private static Map<String, Map<Date, IdentityMapping>> transformIdentities(Set<Module> modules) {
266 Map<String, Map<Date, IdentityMapping>> mappedIds = Maps.newHashMap();
267 for (Module module : modules) {
268 String namespace = module.getNamespace().toString();
269 Map<Date, IdentityMapping> revisionsByNamespace = mappedIds.get(namespace);
270 if (revisionsByNamespace == null) {
271 revisionsByNamespace = Maps.newHashMap();
272 mappedIds.put(namespace, revisionsByNamespace);
275 Date revision = module.getRevision();
277 IdentityMapping identityMapping = revisionsByNamespace.get(revision);
278 if (identityMapping == null) {
279 identityMapping = new IdentityMapping();
280 revisionsByNamespace.put(revision, identityMapping);
283 for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
284 identityMapping.addIdSchemaNode(identitySchemaNode);
292 public Map<String/* Namespace from yang file */,
293 Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs(
294 Map<String/* Namespace from yang file */,
295 Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
296 return transformMbeToModuleConfigs(configRegistryClient, mBeanEntries);
299 public Map<String/* Namespace from yang file */,
300 Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs(BeanReader reader,
301 Map<String/* Namespace from yang file */,
302 Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
304 Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = Maps.newHashMap();
306 for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mBeanEntries.entrySet()) {
307 for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
308 String moduleName = moduleNameToMbe.getKey();
309 ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
311 ModuleConfig moduleConfig = new ModuleConfig(moduleName,
312 new InstanceConfig(reader, moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
314 Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig.get(namespaceToModuleToMbe.getKey());
315 if (moduleNameToModuleConfig == null) {
316 moduleNameToModuleConfig = Maps.newHashMap();
317 namespaceToModuleNameToModuleConfig.put(namespaceToModuleToMbe.getKey(), moduleNameToModuleConfig);
320 moduleNameToModuleConfig.put(moduleName, moduleConfig);
324 return namespaceToModuleNameToModuleConfig;
327 public ConfigExecution getConfigExecution(final Config configMapping, final Element xmlToBePersisted) throws DocumentedException {
328 return new ConfigExecution(configMapping, XmlElement.fromDomElement(xmlToBePersisted), TestOption.testThenSet, EditStrategyType.getDefaultStrategy());
331 private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(ConfigRegistryClient configRegistryClient,
332 Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries) {
333 Map<String, Map<String, ModuleRuntime>> retVal = Maps.newHashMap();
335 for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mBeanEntries.entrySet()) {
337 Map<String, ModuleRuntime> innerMap = Maps.newHashMap();
338 Map<String, ModuleMXBeanEntry> entriesFromNamespace = namespaceToModuleEntry.getValue();
339 for (Map.Entry<String, ModuleMXBeanEntry> moduleToMXEntry : entriesFromNamespace.entrySet()) {
341 ModuleMXBeanEntry mbe = moduleToMXEntry.getValue();
343 Map<RuntimeBeanEntry, InstanceConfig> cache = Maps.newHashMap();
344 RuntimeBeanEntry root = null;
345 for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
346 cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap(), mbe.getNullableDummyContainerName()));
356 InstanceRuntime rootInstanceRuntime = createInstanceRuntime(root, cache);
357 ModuleRuntime moduleRuntime = new ModuleRuntime(rootInstanceRuntime);
358 innerMap.put(moduleToMXEntry.getKey(), moduleRuntime);
361 retVal.put(namespaceToModuleEntry.getKey(), innerMap);
366 private InstanceRuntime createInstanceRuntime(RuntimeBeanEntry root, Map<RuntimeBeanEntry, InstanceConfig> cache) {
367 Map<String, InstanceRuntime> children = Maps.newHashMap();
368 for (RuntimeBeanEntry child : root.getChildren()) {
369 children.put(child.getJavaNamePrefix(), createInstanceRuntime(child, cache));
372 return new InstanceRuntime(cache.get(root), children, createJmxToYangMap(root.getChildren()));
375 private Map<String, String> createJmxToYangMap(List<RuntimeBeanEntry> children) {
376 Map<String, String> jmxToYangNamesForChildRbe = Maps.newHashMap();
377 for (RuntimeBeanEntry rbe : children) {
378 jmxToYangNamesForChildRbe.put(rbe.getJavaNamePrefix(), rbe.getYangName());
380 return jmxToYangNamesForChildRbe;
383 public Element get(Document document) throws DocumentedException {
384 final ObjectName testTransaction = transactionProvider.getOrCreateReadTransaction();
385 final ConfigTransactionClient txClient = configRegistryClient.getConfigTransactionClient(testTransaction);
388 // Runtime beans are not parts of transactions and have to be queried against the central registry
389 final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
391 final Set<ObjectName> configBeans = Datastore.getInstanceQueryStrategy(Datastore.running, transactionProvider)
392 .queryInstances(configRegistryClient);
394 final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(configRegistryClient,
395 yangStoreService.getModuleMXBeanEntryMap());
397 final YangStoreContext yangStoreSnapshot = yangStoreService.getCurrentSnapshot();
398 final Map<String, Map<String, ModuleConfig>> moduleConfigs = transformMbeToModuleConfigs(txClient,
399 yangStoreSnapshot.getModuleMXBeanEntryMap());
401 final org.opendaylight.controller.config.facade.xml.runtime.Runtime runtime = new Runtime(moduleRuntimes, moduleConfigs);
403 return runtime.toXml(runtimeBeans, configBeans, document, yangStoreSnapshot.getEnumResolver());
405 transactionProvider.closeReadTransaction();
409 public void abortConfiguration() {
410 if (transactionProvider.getTransaction().isPresent()) {
411 this.transactionProvider.abortTransaction();
415 public void validateConfiguration() throws ValidationException {
416 transactionProvider.validateTransaction();
420 public void close() {
421 transactionProvider.close();
424 public RpcFacade getRpcFacade() {