1 package org.opendaylight.controller.sal.restconf.impl
3 import com.google.common.base.Preconditions
4 import com.google.common.collect.BiMap
5 import com.google.common.collect.FluentIterable
6 import com.google.common.collect.HashBiMap
8 import java.net.URLDecoder
9 import java.net.URLEncoder
10 import java.util.ArrayList
11 import java.util.HashMap
14 import java.util.concurrent.ConcurrentHashMap
15 import org.opendaylight.controller.sal.core.api.mount.MountInstance
16 import org.opendaylight.controller.sal.core.api.mount.MountService
17 import org.opendaylight.controller.sal.rest.impl.RestUtil
18 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
19 import org.opendaylight.yangtools.yang.common.QName
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
23 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
24 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
25 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
26 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
27 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
34 import org.opendaylight.yangtools.yang.model.api.Module
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext
37 import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener
38 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
39 import org.slf4j.LoggerFactory
41 import static com.google.common.base.Preconditions.*
42 import static javax.ws.rs.core.Response.Status.*
44 class ControllerContext implements SchemaServiceListener {
45 val static LOG = LoggerFactory.getLogger(ControllerContext)
46 val static ControllerContext INSTANCE = new ControllerContext
47 val static NULL_VALUE = "null"
48 val static MOUNT_MODULE = "yang-ext"
49 val static MOUNT_NODE = "mount"
50 public val static MOUNT = "yang-ext:mount"
53 var SchemaContext globalSchema;
56 var MountService mountService;
58 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
59 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
60 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
63 if (INSTANCE !== null) {
64 throw new IllegalStateException("Already instantiated");
68 static def getInstance() {
72 private def void checkPreconditions() {
73 if (globalSchema === null) {
74 throw new ResponseException(SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
78 def setSchemas(SchemaContext schemas) {
79 onGlobalContextUpdated(schemas)
82 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
84 val pathArgs = restconfInstance.split("/");
88 if (pathArgs.head.empty) {
91 val startModule = pathArgs.head.toModuleName();
92 if (startModule === null) {
93 throw new ResponseException(BAD_REQUEST, "First node in URI has to be in format \"moduleName:nodeName\"")
95 val iiWithSchemaNode = collectPathArguments(InstanceIdentifier.builder(), pathArgs,
96 globalSchema.getLatestModule(startModule), null);
97 if (iiWithSchemaNode === null) {
98 throw new ResponseException(BAD_REQUEST, "URI has bad format")
100 return iiWithSchemaNode
103 private def getLatestModule(SchemaContext schema, String moduleName) {
104 checkArgument(schema !== null);
105 checkArgument(moduleName !== null && !moduleName.empty)
106 val modules = schema.modules.filter[m|m.name == moduleName]
107 return modules.filterLatestModule
110 private def filterLatestModule(Iterable<Module> modules) {
111 var latestModule = modules.head
112 for (module : modules) {
113 if (module.revision.after(latestModule.revision)) {
114 latestModule = module
120 def findModuleByName(String moduleName) {
122 checkArgument(moduleName !== null && !moduleName.empty)
123 return globalSchema.getLatestModule(moduleName)
126 def findModuleByName(MountInstance mountPoint, String moduleName) {
127 checkArgument(moduleName !== null && mountPoint !== null)
128 val mountPointSchema = mountPoint.schemaContext;
129 return mountPointSchema?.getLatestModule(moduleName);
132 def findModuleByNamespace(URI namespace) {
134 checkArgument(namespace !== null)
135 val moduleSchemas = globalSchema.findModuleByNamespace(namespace)
136 return moduleSchemas?.filterLatestModule
139 def findModuleByNamespace(MountInstance mountPoint, URI namespace) {
140 checkArgument(namespace !== null && mountPoint !== null)
141 val mountPointSchema = mountPoint.schemaContext;
142 val moduleSchemas = mountPointSchema?.findModuleByNamespace(namespace)
143 return moduleSchemas?.filterLatestModule
146 def String toFullRestconfIdentifier(InstanceIdentifier path) {
148 val elements = path.path;
149 val ret = new StringBuilder();
150 val startQName = elements.get(0).nodeType;
151 val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
152 var node = initialModule as DataSchemaNode;
153 for (element : elements) {
154 node = node.childByQName(element.nodeType);
155 ret.append(element.toRestconfIdentifier(node));
160 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
161 '''/«argument.nodeType.toRestconfIdentifier()»'''
164 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
165 val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
166 val keyValues = argument.keyValues;
167 return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
170 private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
171 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
174 def findModuleNameByNamespace(URI namespace) {
176 var moduleName = uriToModuleName.get(namespace)
177 if (moduleName === null) {
178 val module = findModuleByNamespace(namespace)
179 if (module === null) return null
180 moduleName = module.name
181 uriToModuleName.put(namespace, moduleName)
186 def findModuleNameByNamespace(MountInstance mountPoint, URI namespace) {
187 val module = mountPoint.findModuleByNamespace(namespace);
191 def findNamespaceByModuleName(String moduleName) {
192 var namespace = moduleNameToUri.get(moduleName)
193 if (namespace === null) {
194 var module = findModuleByName(moduleName)
195 if(module === null) return null
196 namespace = module.namespace
197 uriToModuleName.put(namespace, moduleName)
202 def findNamespaceByModuleName(MountInstance mountPoint, String moduleName) {
203 val module = mountPoint.findModuleByName(moduleName)
204 return module?.namespace
207 def CharSequence toRestconfIdentifier(QName qname) {
209 var module = uriToModuleName.get(qname.namespace)
210 if (module === null) {
211 val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
212 if(moduleSchema === null) throw new IllegalArgumentException()
213 uriToModuleName.put(qname.namespace, moduleSchema.name)
214 module = moduleSchema.name;
216 return '''«module»:«qname.localName»''';
219 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
220 for (caze : container.cases) {
221 val ret = caze.childByQName(name)
229 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
230 val ret = container.getDataChildByName(name);
234 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
235 return container.dataNodeChildByQName(name);
238 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
239 return container.dataNodeChildByQName(name);
242 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
246 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
247 var ret = container.getDataChildByName(name);
250 // Find in Choice Cases
251 for (node : container.childNodes) {
252 if (node instanceof ChoiceCaseNode) {
253 val caseNode = (node as ChoiceCaseNode);
254 ret = caseNode.childByQName(name);
264 private def toUriString(Object object) {
265 if(object === null) return "";
266 return URLEncoder.encode(object.toString)
269 private def InstanceIdWithSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
270 DataNodeContainer parentNode, MountInstance mountPoint) {
271 checkNotNull(strings)
272 if (parentNode === null) {
276 return new InstanceIdWithSchemaNode(builder.toInstance, parentNode as DataSchemaNode, mountPoint)
279 val nodeName = strings.head.toNodeName
280 val moduleName = strings.head.toModuleName
281 var DataSchemaNode targetNode = null
282 if (!moduleName.nullOrEmpty) {
283 // if it is mount point
284 if (moduleName == MOUNT_MODULE && nodeName == MOUNT_NODE) {
285 if (mountPoint !== null) {
286 throw new ResponseException(BAD_REQUEST, "Restconf supports just one mount point in URI.")
289 if (mountService === null) {
290 throw new ResponseException(SERVICE_UNAVAILABLE, "MountService was not found. "
291 + "Finding behind mount points does not work."
295 val partialPath = builder.toInstance;
296 val mount = mountService.getMountPoint(partialPath)
297 if (mount === null) {
298 LOG.debug("Instance identifier to missing mount point: {}", partialPath)
299 throw new ResponseException(BAD_REQUEST, "Mount point does not exist.")
302 val mountPointSchema = mount.schemaContext;
303 if (mountPointSchema === null) {
304 throw new ResponseException(BAD_REQUEST, "Mount point does not contain any schema with modules.")
307 if (strings.size == 1) { // any data node is not behind mount point
308 return new InstanceIdWithSchemaNode(InstanceIdentifier.builder().toInstance, mountPointSchema, mount)
311 val moduleNameBehindMountPoint = strings.get(1).toModuleName()
312 if (moduleNameBehindMountPoint === null) {
313 throw new ResponseException(BAD_REQUEST,
314 "First node after mount point in URI has to be in format \"moduleName:nodeName\"")
317 val moduleBehindMountPoint = mountPointSchema.getLatestModule(moduleNameBehindMountPoint)
318 if (moduleBehindMountPoint === null) {
319 throw new ResponseException(BAD_REQUEST,
320 "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
323 return collectPathArguments(InstanceIdentifier.builder(), strings.subList(1, strings.size),
324 moduleBehindMountPoint, mount);
327 var Module module = null;
328 if (mountPoint === null) {
329 module = globalSchema.getLatestModule(moduleName)
330 if (module === null) {
331 throw new ResponseException(BAD_REQUEST,
332 "URI has bad format. \"" + moduleName + "\" module does not exist.")
335 module = mountPoint.schemaContext?.getLatestModule(moduleName)
336 if (module === null) {
337 throw new ResponseException(BAD_REQUEST,
338 "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
341 targetNode = parentNode.findInstanceDataChildByNameAndNamespace(nodeName, module.namespace)
342 if (targetNode === null) {
343 throw new ResponseException(BAD_REQUEST, "URI has bad format. Possible reasons:\n" +
344 "1. \"" + strings.head + "\" was not found in parent data node.\n" +
345 "2. \"" + strings.head + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + strings.head + "\".")
347 } else { // string without module name
348 val potentialSchemaNodes = parentNode.findInstanceDataChildrenByName(nodeName)
349 if (potentialSchemaNodes.size > 1) {
350 val StringBuilder namespacesOfPotentialModules = new StringBuilder;
351 for (potentialNodeSchema : potentialSchemaNodes) {
352 namespacesOfPotentialModules.append(" ").append(potentialNodeSchema.QName.namespace.toString).append("\n")
354 throw new ResponseException(BAD_REQUEST, "URI has bad format. Node \"" + nodeName + "\" is added as augment from more than one module. "
355 + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
356 + "\nThe node is added as augment from modules with namespaces:\n" + namespacesOfPotentialModules)
358 targetNode = potentialSchemaNodes.head
359 if (targetNode === null) {
360 throw new ResponseException(BAD_REQUEST, "URI has bad format. \"" + nodeName + "\" was not found in parent data node.\n")
364 if (!(targetNode instanceof ListSchemaNode) && !(targetNode instanceof ContainerSchemaNode)) {
365 throw new ResponseException(BAD_REQUEST,"URI has bad format. Node \"" + strings.head + "\" must be Container or List yang type.")
367 // Number of consumed elements
369 if (targetNode instanceof ListSchemaNode) {
370 val listNode = targetNode as ListSchemaNode;
371 val keysSize = listNode.keyDefinition.size
373 // every key has to be filled
374 if ((strings.length - consumed) < keysSize) {
375 throw new ResponseException(BAD_REQUEST,"Missing key for list \"" + listNode.QName.localName + "\".")
377 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
378 val keyValues = new HashMap<QName, Object>();
380 for (key : listNode.keyDefinition) {
381 val uriKeyValue = uriKeyValues.get(i);
383 // key value cannot be NULL
384 if (uriKeyValue.equals(NULL_VALUE)) {
385 throw new ResponseException(BAD_REQUEST, "URI has bad format. List \"" + listNode.QName.localName
386 + "\" cannot contain \"null\" value as a key."
389 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
392 consumed = consumed + i;
393 builder.nodeWithKey(targetNode.QName, keyValues);
396 // Only one instance of node is allowed
397 builder.node(targetNode.QName);
399 if (targetNode instanceof DataNodeContainer) {
400 val remaining = strings.subList(consumed, strings.length);
401 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer, mountPoint);
405 return new InstanceIdWithSchemaNode(builder.toInstance, targetNode, mountPoint)
408 def DataSchemaNode findInstanceDataChildByNameAndNamespace(DataNodeContainer container,
409 String name, URI namespace) {
410 Preconditions.checkNotNull(namespace)
411 val potentialSchemaNodes = container.findInstanceDataChildrenByName(name)
412 return potentialSchemaNodes.filter[n|n.QName.namespace == namespace].head
415 def List<DataSchemaNode> findInstanceDataChildrenByName(DataNodeContainer container, String name) {
416 Preconditions.checkNotNull(container)
417 Preconditions.checkNotNull(name)
418 val instantiatedDataNodeContainers = new ArrayList
419 instantiatedDataNodeContainers.collectInstanceDataNodeContainers(container, name)
420 return instantiatedDataNodeContainers
423 private def void collectInstanceDataNodeContainers(List<DataSchemaNode> potentialSchemaNodes, DataNodeContainer container,
425 val nodes = container.childNodes.filter[n|n.QName.localName == name]
426 for (potentialNode : nodes) {
427 if (potentialNode.isInstantiatedDataSchema) {
428 potentialSchemaNodes.add(potentialNode)
431 val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
432 for (caze : allCases) {
433 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name)
437 def boolean isInstantiatedDataSchema(DataSchemaNode node) {
439 LeafSchemaNode: return true
440 LeafListSchemaNode: return true
441 ContainerSchemaNode: return true
442 ListSchemaNode: return true
443 default: return false
447 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
448 checkNotNull(uriValue);
449 checkArgument(node instanceof LeafSchemaNode);
450 val urlDecoded = URLDecoder.decode(uriValue);
451 val typedef = (node as LeafSchemaNode).type;
453 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
454 if(decoded === null) {
455 var baseType = RestUtil.resolveBaseTypeFrom(typedef)
456 if(baseType instanceof IdentityrefTypeDefinition) {
457 decoded = toQName(urlDecoded)
460 map.put(node.QName, decoded);
463 private static def String toModuleName(String str) {
465 if (str.contains(":")) {
466 val args = str.split(":");
467 if (args.size === 2) {
474 private def String toNodeName(String str) {
475 if (str.contains(":")) {
476 val args = str.split(":");
477 if (args.size === 2) {
484 private def QName toQName(String name) {
485 val module = name.toModuleName;
486 val node = name.toNodeName;
487 val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
488 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
490 return QName.create(namespace,node);
493 def getRpcDefinition(String name) {
494 return qnameToRpc.get(name.toQName)
497 override onGlobalContextUpdated(SchemaContext context) {
498 this.globalSchema = context;
499 for (operation : context.operations) {
500 val qname = operation.QName;
501 qnameToRpc.put(qname, operation);