2 * Copyright (c) 2013 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.netconf.confignetconfconnector.mapping.config;
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.HashMultimap;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Sets;
18 import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
19 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
20 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
21 import org.opendaylight.controller.netconf.util.xml.XmlElement;
22 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
23 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Document;
27 import org.w3c.dom.Element;
29 import javax.management.ObjectName;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
39 public final class Services {
41 private static final Logger logger = LoggerFactory.getLogger(Services.class);
43 private static final String PROVIDER_KEY = "provider";
44 private static final String NAME_KEY = "name";
45 public static final String TYPE_KEY = "type";
46 public static final String SERVICE_KEY = "service";
48 private long suffix = 1;
50 private final Map<String /*Namespace*/, Map<String/* ServiceName */, Map<String/* refName */, ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = Maps
52 private ServiceReferenceReadableRegistry configServiceRefRegistry;
54 public Services(ServiceReferenceReadableRegistry configServiceRefRegistry) {
55 this.configServiceRefRegistry = configServiceRefRegistry;
59 public String getNewDefaultRefName(String namespace, String serviceName, String moduleName, String instanceName) {
61 refName = "ref_" + instanceName;
63 Map<String, Map<String, String>> serviceNameToRefNameToInstance = getMappedServices().get(namespace);
65 Map<String, String> refNameToInstance;
66 if(serviceNameToRefNameToInstance == null || serviceNameToRefNameToInstance.containsKey(serviceName) == false) {
67 refNameToInstance = Collections.emptyMap();
69 refNameToInstance = serviceNameToRefNameToInstance.get(serviceName);
71 final Set<String> refNamesAsSet = toSet(refNameToInstance.keySet());
72 if (refNamesAsSet.contains(refName)) {
73 refName = findAvailableRefName(refName, refNamesAsSet);
79 private Set<String> toSet(Collection<String> values) {
80 Set<String> refNamesAsSet = Sets.newHashSet();
82 for (String refName : values) {
83 boolean resultAdd = refNamesAsSet.add(refName);
84 Preconditions.checkState(resultAdd,
85 "Error occurred building services element, reference name {} was present twice", refName);
91 public ServiceInstance getByServiceAndRefName(String namespace, String serviceName, String refName) {
92 Map<String, Map<String, String>> serviceNameToRefNameToInstance = getMappedServices().get(namespace);
94 Preconditions.checkArgument(serviceNameToRefNameToInstance != null, "No serviceInstances mapped to " + namespace);
96 Map<String, String> refNameToInstance = serviceNameToRefNameToInstance.get(serviceName);
97 Preconditions.checkArgument(refNameToInstance != null, "No serviceInstances mapped to " + serviceName + " , "
98 + serviceNameToRefNameToInstance.keySet());
100 ServiceInstance serviceInstance = ServiceInstance.fromString(refNameToInstance.get(refName));
101 Preconditions.checkArgument(serviceInstance != null, "No serviceInstance mapped to " + refName
102 + " under service name " + serviceName + " , " + refNameToInstance.keySet());
103 return serviceInstance;
106 // TODO hide getMappedServices, call it explicitly in toXml
108 public Map<String, Map<String, Map<String, String>>> getMappedServices() {
109 Map<String, Map<String, Map<String, String>>> retVal = Maps.newHashMap();
111 for (String namespace : namespaceToServiceNameToRefNameToInstance.keySet()) {
113 Map<String, Map<String, ServiceInstance>> serviceNameToRefNameToInstance = namespaceToServiceNameToRefNameToInstance
115 Map<String, Map<String, String>> innerRetVal = Maps.newHashMap();
117 for (String serviceName : serviceNameToRefNameToInstance.keySet()) {
119 Map<String, String> innerInnerRetVal = Maps.newHashMap();
120 for (Entry<String, ServiceInstance> refNameToSi : serviceNameToRefNameToInstance.get(serviceName).entrySet()) {
121 innerInnerRetVal.put(refNameToSi.getKey(), refNameToSi.getValue().toString());
123 innerRetVal.put(serviceName, innerInnerRetVal);
125 retVal.put(namespace, innerRetVal);
128 Map<String, Map<String, ObjectName>> serviceMapping = configServiceRefRegistry.getServiceMapping();
129 for (String serviceQName : serviceMapping.keySet())
130 for (String refName : serviceMapping.get(serviceQName).keySet()) {
132 ObjectName on = serviceMapping.get(serviceQName).get(refName);
133 ServiceInstance si = ServiceInstance.fromObjectName(on);
135 // FIXME use QName's new String constructor, after its implemented
136 Pattern p = Pattern.compile("\\(([^\\(\\?]+)\\?[^\\?\\)]*\\)([^\\)]+)");
137 Matcher matcher = p.matcher(serviceQName);
138 Preconditions.checkArgument(matcher.matches());
139 String namespace = matcher.group(1);
140 String localName = matcher.group(2);
142 Map<String, Map<String, String>> serviceToRefs = retVal.get(namespace);
143 if(serviceToRefs==null) {
144 serviceToRefs = Maps.newHashMap();
145 retVal.put(namespace, serviceToRefs);
148 Map<String, String> refsToSis = serviceToRefs.get(localName);
149 if(refsToSis==null) {
150 refsToSis = Maps.newHashMap();
151 serviceToRefs.put(localName, refsToSis);
154 Preconditions.checkState(refsToSis.containsKey(refName) == false,
155 "Duplicate reference name %s for service %s:%s, now for instance %s", refName, namespace,
157 refsToSis.put(refName, si.toString());
166 public Map<String, Map<String, Map<String, ServiceInstance>>> getNamespaceToServiceNameToRefNameToInstance() {
167 return namespaceToServiceNameToRefNameToInstance;
170 // TODO hide resolveServices, call it explicitly in fromXml
172 public static Services resolveServices(Map<String, Map<String, Map<String, String>>> mappedServices, ServiceReferenceReadableRegistry taClient) {
173 Services tracker = new Services(taClient);
175 for (Entry<String, Map<String, Map<String, String>>> namespaceEntry : mappedServices.entrySet()) {
176 String namespace = namespaceEntry.getKey();
178 for (Entry<String, Map<String, String>> serviceEntry : namespaceEntry.getValue().entrySet()) {
180 String serviceName = serviceEntry.getKey();
181 for (Entry<String, String> refEntry : serviceEntry.getValue().entrySet()) {
183 Map<String, Map<String, ServiceInstance>> namespaceToServices = tracker.namespaceToServiceNameToRefNameToInstance.get(namespace);
184 if (namespaceToServices == null) {
185 namespaceToServices = Maps.newHashMap();
186 tracker.namespaceToServiceNameToRefNameToInstance.put(namespace, namespaceToServices);
189 Map<String, ServiceInstance> refNameToInstance = namespaceToServices
191 if (refNameToInstance == null) {
192 refNameToInstance = Maps.newHashMap();
193 namespaceToServices.put(serviceName, refNameToInstance);
196 String refName = refEntry.getKey();
198 ServiceInstance serviceInstance = ServiceInstance.fromString(refEntry.getValue());
199 refNameToInstance.put(refName, serviceInstance);
207 // TODO support edit strategies on services
209 public static Map<String, Map<String, Map<String, String>>> fromXml(XmlElement xml) {
210 Map<String, Map<String, Map<String, String>>> retVal = Maps.newHashMap();
212 List<XmlElement> services = xml.getChildElements(SERVICE_KEY);
213 xml.checkUnrecognisedElements(services);
215 for (XmlElement service : services) {
217 XmlElement typeElement = service.getOnlyChildElement(TYPE_KEY);
218 Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
220 Preconditions.checkState(prefixNamespace.getKey()!=null && prefixNamespace.getKey().equals("") == false, "Type attribute was not prefixed");
222 Map<String, Map<String, String>> namespaceToServices = retVal.get(prefixNamespace.getValue());
223 if(namespaceToServices == null) {
224 namespaceToServices = Maps.newHashMap();
225 retVal.put(prefixNamespace.getValue(), namespaceToServices);
228 String serviceName = ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
230 Map<String, String> innerMap = Maps.newHashMap();
231 namespaceToServices.put(serviceName, innerMap);
233 List<XmlElement> instances = service.getChildElements(XmlNetconfConstants.INSTANCE_KEY);
234 service.checkUnrecognisedElements(instances, typeElement);
236 for (XmlElement instance : instances) {
237 XmlElement nameElement = instance.getOnlyChildElement(NAME_KEY);
238 String refName = nameElement.getTextContent();
240 XmlElement providerElement = instance.getOnlyChildElement(PROVIDER_KEY);
241 String providerName = providerElement.getTextContent();
243 instance.checkUnrecognisedElements(nameElement, providerElement);
245 innerMap.put(refName, providerName);
252 private String findAvailableRefName(String refName, Set<String> refNamesAsSet) {
253 String intitialRefName = refName;
256 refName = intitialRefName + "_" + suffix++;
257 if (refNamesAsSet.contains(refName) == false)
262 public Element toXml(Map<String, Map<String, Map<String, String>>> mappedServices, Document document) {
263 Element root = document.createElement(XmlNetconfConstants.SERVICES_KEY);
264 XmlUtil.addNamespaceAttr(root, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
266 for (String namespace : mappedServices.keySet()) {
268 for (Entry<String, Map<String, String>> serviceEntry : mappedServices.get(namespace).entrySet()) {
269 Element serviceElement = document.createElement(SERVICE_KEY);
270 root.appendChild(serviceElement);
272 Element typeElement = XmlUtil.createPrefixedTextElement(document, TYPE_KEY, XmlNetconfConstants.PREFIX,
273 serviceEntry.getKey());
274 XmlUtil.addPrefixedNamespaceAttr(typeElement, XmlNetconfConstants.PREFIX, namespace);
275 serviceElement.appendChild(typeElement);
277 for (Entry<String, String> instanceEntry : serviceEntry.getValue().entrySet()) {
278 Element instanceElement = document.createElement(XmlNetconfConstants.INSTANCE_KEY);
279 serviceElement.appendChild(instanceElement);
281 Element nameElement = XmlUtil.createTextElement(document, NAME_KEY, instanceEntry.getKey());
282 instanceElement.appendChild(nameElement);
284 Element providerElement = XmlUtil.createTextElement(document, PROVIDER_KEY, instanceEntry.getValue());
285 instanceElement.appendChild(providerElement);
293 public String getRefName(String namespace, String serviceName, ObjectName on, Optional<String> expectedRefName) {
294 Optional<String> refNameOptional = getRefNameOptional(namespace, serviceName, on, expectedRefName);
295 Preconditions.checkState(refNameOptional.isPresent(), "No reference names mapped to %s, %s, %s", namespace,
297 return refNameOptional.get();
300 public Optional<String> getRefNameOptional(String namespace, String serviceName, ObjectName on,
301 Optional<String> expectedRefName) {
302 Map<String, Map<String, String>> services = getMappedServices().get(namespace);
304 if(services == null) return Optional.absent();
305 Map<String, String> refs = services.get(serviceName);
307 if(refs == null) return Optional.absent();
308 Multimap<ServiceInstance, String> reverted = revertMap(refs);
310 ServiceInstance serviceInstance = ServiceInstance.fromObjectName(on);
311 Collection<String> references = reverted.get(serviceInstance);
313 if (expectedRefName.isPresent() && references.contains(expectedRefName.get())) {
314 logger.debug("Returning expected ref name {} for {}", expectedRefName.get(), on);
315 return expectedRefName;
316 } else if (references.size() > 0) {
317 String next = references.iterator().next();
318 logger.debug("Returning random ref name {} for {}", next, on);
319 return Optional.of(next);
321 return Optional.absent();
324 private Multimap<ServiceInstance, String> revertMap(Map<String, String> refs) {
325 Multimap<ServiceInstance, String> multimap = HashMultimap.create();
327 for (Entry<String, String> e : refs.entrySet()) {
328 multimap.put(ServiceInstance.fromString(e.getValue()), e.getKey());
334 public boolean hasRefName(String key, String value, ObjectName on) {
335 return getRefNameOptional(key, value, on, Optional.<String>absent()).isPresent();
338 public static final class ServiceInstance {
339 public ServiceInstance(String moduleName, String instanceName) {
340 this.moduleName = moduleName;
341 this.instanceName = instanceName;
344 public static ServiceInstance fromString(String instanceId) {
345 instanceId = instanceId.trim();
346 Matcher matcher = p.matcher(instanceId);
347 if(matcher.matches() == false) {
348 matcher = pDeprecated.matcher(instanceId);
351 Preconditions.checkArgument(matcher.matches(), "Unexpected format for provider, expected " + p.toString()
352 + " or " + pDeprecated.toString() + " but was " + instanceId);
354 String factoryName = matcher.group(1);
355 String instanceName = matcher.group(2);
356 return new ServiceInstance(factoryName, instanceName);
359 private final String moduleName, instanceName;
360 private String serviceName;
362 public String getServiceName() {
366 public void setServiceName(String serviceName) {
367 this.serviceName = serviceName;
370 public String getModuleName() {
374 public String getInstanceName() {
378 private static final String blueprint = "/"
379 + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "["
380 + XmlNetconfConstants.TYPE_KEY + "='%s']["
381 + XmlNetconfConstants.NAME_KEY + "='%s']";
383 // TODO unify with xpath in RuntimeRpc
385 // Previous version of xpath, needs to be supported for backwards compatibility (persisted configs by config-persister)
386 private static final String blueprintRDeprecated = "/" + XmlNetconfConstants.CONFIG_KEY + "/"
387 + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "\\["
388 + XmlNetconfConstants.NAME_KEY + "='%s'\\]/" + XmlNetconfConstants.INSTANCE_KEY + "\\["
389 + XmlNetconfConstants.NAME_KEY + "='%s'\\]";
391 private static final String blueprintR = "/"
392 + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "\\["
393 + XmlNetconfConstants.TYPE_KEY + "='%s'\\]\\["
394 + XmlNetconfConstants.NAME_KEY + "='%s'\\]";
396 private static final Pattern pDeprecated = Pattern.compile(String.format(blueprintRDeprecated, "(.+)", "(.+)"));
397 private static final Pattern p = Pattern.compile(String.format(blueprintR, "(.+)", "(.+)"));
400 public String toString() {
401 return String.format(blueprint, moduleName, instanceName);
405 public int hashCode() {
406 final int prime = 31;
408 result = prime * result + ((instanceName == null) ? 0 : instanceName.hashCode());
409 result = prime * result + ((moduleName == null) ? 0 : moduleName.hashCode());
414 public boolean equals(Object obj) {
419 if (getClass() != obj.getClass())
421 ServiceInstance other = (ServiceInstance) obj;
422 if (instanceName == null) {
423 if (other.instanceName != null)
425 } else if (!instanceName.equals(other.instanceName))
427 if (moduleName == null) {
428 if (other.moduleName != null)
430 } else if (!moduleName.equals(other.moduleName))
435 public ObjectName getObjectName(String transactionName) {
436 return ObjectNameUtil.createTransactionModuleON(transactionName, moduleName, instanceName);
439 public static ServiceInstance fromObjectName(ObjectName on) {
440 return new ServiceInstance(ObjectNameUtil.getFactoryName(on), ObjectNameUtil.getInstanceName(on));