1 package org.opendaylight.controller.sal.restconf.impl
3 import com.google.common.collect.BiMap
4 import com.google.common.collect.FluentIterable
5 import com.google.common.collect.HashBiMap
7 import java.net.URLDecoder
8 import java.net.URLEncoder
9 import java.util.HashMap
12 import java.util.concurrent.ConcurrentHashMap
13 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener
14 import org.opendaylight.controller.sal.core.api.mount.MountService
15 import org.opendaylight.controller.sal.rest.impl.RestUtil
16 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
17 import org.opendaylight.yangtools.yang.common.QName
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
23 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec
24 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
25 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
29 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
32 import org.opendaylight.yangtools.yang.model.api.Module
33 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext
35 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
36 import org.slf4j.LoggerFactory
38 import static com.google.common.base.Preconditions.*
39 import static javax.ws.rs.core.Response.Status.*
40 import org.opendaylight.controller.sal.core.api.mount.MountInstance
42 class ControllerContext implements SchemaServiceListener {
43 val static LOG = LoggerFactory.getLogger(ControllerContext)
44 val static ControllerContext INSTANCE = new ControllerContext
45 val static NULL_VALUE = "null"
46 val static MOUNT_MODULE = "yang-ext"
47 val static MOUNT_NODE = "mount"
48 val static MOUNT = "yang-ext:mount"
51 var SchemaContext globalSchema;
54 var MountService mountService;
56 private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
57 private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
58 private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
61 if (INSTANCE !== null) {
62 throw new IllegalStateException("Already instantiated");
66 static def getInstance() {
70 private def void checkPreconditions() {
71 if (globalSchema === null) {
72 throw new ResponseException(SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
76 def setSchemas(SchemaContext schemas) {
77 onGlobalContextUpdated(schemas)
80 public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
82 val pathArgs = restconfInstance.split("/");
86 if (pathArgs.head.empty) {
89 val startModule = pathArgs.head.toModuleName();
90 if (startModule === null) {
91 throw new ResponseException(BAD_REQUEST, "First node in URI has to be in format \"moduleName:nodeName\"")
93 val iiWithSchemaNode = collectPathArguments(InstanceIdentifier.builder(), pathArgs,
94 globalSchema.getLatestModule(startModule), null);
95 if (iiWithSchemaNode === null) {
96 throw new ResponseException(BAD_REQUEST, "URI has bad format")
98 return iiWithSchemaNode
101 private def getLatestModule(SchemaContext schema, String moduleName) {
102 checkArgument(schema !== null);
103 checkArgument(moduleName !== null && !moduleName.empty)
104 val modules = schema.modules.filter[m|m.name == moduleName]
105 return modules.filterLatestModule
108 private def filterLatestModule(Iterable<Module> modules) {
109 var latestModule = modules.head
110 for (module : modules) {
111 if (module.revision.after(latestModule.revision)) {
112 latestModule = module
118 def findModuleByName(String moduleName) {
120 checkArgument(moduleName !== null && !moduleName.empty)
121 return globalSchema.getLatestModule(moduleName)
124 def findModuleByName(MountInstance mountPoint, String moduleName) {
125 checkArgument(moduleName !== null && mountPoint !== null)
126 val mountPointSchema = mountPoint.schemaContext;
127 return mountPointSchema?.getLatestModule(moduleName);
130 def findModuleByNamespace(URI namespace) {
132 val moduleSchemas = globalSchema.findModuleByNamespace(namespace)
133 return moduleSchemas?.filterLatestModule
136 def findModuleByNamespace(MountInstance mountPoint, URI namespace) {
137 checkArgument(namespace !== null && mountPoint !== null)
138 val mountPointSchema = mountPoint.schemaContext;
139 val moduleSchemas = mountPointSchema?.findModuleByNamespace(namespace)
140 return moduleSchemas?.filterLatestModule
143 def String toFullRestconfIdentifier(InstanceIdentifier path) {
145 val elements = path.path;
146 val ret = new StringBuilder();
147 val startQName = elements.get(0).nodeType;
148 val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
149 var node = initialModule as DataSchemaNode;
150 for (element : elements) {
151 node = node.childByQName(element.nodeType);
152 ret.append(element.toRestconfIdentifier(node));
157 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
158 '''/«argument.nodeType.toRestconfIdentifier()»'''
161 private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
162 val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
163 val keyValues = argument.keyValues;
164 return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
167 private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
168 throw new IllegalArgumentException("Conversion of generic path argument is not supported");
171 def findModuleNameByNamespace(URI namespace) {
173 var module = uriToModuleName.get(namespace)
174 if (module === null) {
175 val moduleSchemas = globalSchema.findModuleByNamespace(namespace);
176 if(moduleSchemas === null) return null
177 var latestModule = moduleSchemas.filterLatestModule
178 if(latestModule === null) return null
179 uriToModuleName.put(namespace, latestModule.name)
180 module = latestModule.name;
185 def findNamespaceByModuleName(String module) {
186 var namespace = moduleNameToUri.get(module)
187 if (namespace === null) {
188 var latestModule = globalSchema.getLatestModule(module)
189 if(latestModule === null) return null
190 namespace = latestModule.namespace
191 uriToModuleName.put(namespace, latestModule.name)
196 def CharSequence toRestconfIdentifier(QName qname) {
198 var module = uriToModuleName.get(qname.namespace)
199 if (module === null) {
200 val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
201 if(moduleSchema === null) throw new IllegalArgumentException()
202 uriToModuleName.put(qname.namespace, moduleSchema.name)
203 module = moduleSchema.name;
205 return '''«module»:«qname.localName»''';
208 private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
209 for (caze : container.cases) {
210 val ret = caze.childByQName(name)
218 private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
219 val ret = container.getDataChildByName(name);
223 private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
224 return container.dataNodeChildByQName(name);
227 private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
228 return container.dataNodeChildByQName(name);
231 private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
235 private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
236 var ret = container.getDataChildByName(name);
239 // Find in Choice Cases
240 for (node : container.childNodes) {
241 if (node instanceof ChoiceCaseNode) {
242 val caseNode = (node as ChoiceCaseNode);
243 ret = caseNode.childByQName(name);
253 private def toUriString(Object object) {
254 if(object === null) return "";
255 return URLEncoder.encode(object.toString)
258 private def InstanceIdWithSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
259 DataNodeContainer parentNode, MountInstance mountPoint) {
260 checkNotNull(strings)
261 if (parentNode === null) {
265 return new InstanceIdWithSchemaNode(builder.toInstance, parentNode as DataSchemaNode, mountPoint)
268 val nodeName = strings.head.toNodeName
269 val moduleName = strings.head.toModuleName
270 var DataSchemaNode targetNode = null
271 if (!moduleName.nullOrEmpty) {
272 // if it is mount point
273 if (moduleName == MOUNT_MODULE && nodeName == MOUNT_NODE) {
274 if (mountPoint !== null) {
275 throw new ResponseException(BAD_REQUEST, "Restconf supports just one mount point in URI.")
278 if (mountService === null) {
279 throw new ResponseException(SERVICE_UNAVAILABLE, "MountService was not found. "
280 + "Finding behind mount points does not work."
284 val partialPath = builder.toInstance;
285 val mount = mountService.getMountPoint(partialPath)
286 if (mount === null) {
287 LOG.debug("Instance identifier to missing mount point: {}", partialPath)
288 throw new ResponseException(BAD_REQUEST, "Mount point does not exist.")
291 val mountPointSchema = mount.schemaContext;
292 if (mountPointSchema === null) {
293 throw new ResponseException(BAD_REQUEST, "Mount point does not contain any schema with modules.")
296 if (strings.size == 1) { // any data node is not behind mount point
297 return new InstanceIdWithSchemaNode(InstanceIdentifier.builder().toInstance, mountPointSchema, mount)
300 val moduleNameBehindMountPoint = strings.get(1).toModuleName()
301 if (moduleNameBehindMountPoint === null) {
302 throw new ResponseException(BAD_REQUEST,
303 "First node after mount point in URI has to be in format \"moduleName:nodeName\"")
306 val moduleBehindMountPoint = mountPointSchema.getLatestModule(moduleNameBehindMountPoint)
307 if (moduleBehindMountPoint === null) {
308 throw new ResponseException(BAD_REQUEST,
309 "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
312 return collectPathArguments(InstanceIdentifier.builder(), strings.subList(1, strings.size),
313 moduleBehindMountPoint, mount);
316 var Module module = null;
317 if (mountPoint === null) {
318 module = globalSchema.getLatestModule(moduleName)
319 if (module === null) {
320 throw new ResponseException(BAD_REQUEST,
321 "URI has bad format. \"" + moduleName + "\" module does not exist.")
324 module = mountPoint.schemaContext?.getLatestModule(moduleName)
325 if (module === null) {
326 throw new ResponseException(BAD_REQUEST,
327 "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
330 targetNode = parentNode.findInstanceDataChild(nodeName, module.namespace)
331 if (targetNode === null) {
332 throw new ResponseException(BAD_REQUEST, "URI has bad format. Possible reasons:\n" +
333 "1. \"" + strings.head + "\" was not found in parent data node.\n" +
334 "2. \"" + strings.head + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + strings.head + "\".")
336 } else { // string without module name
337 targetNode = parentNode.findInstanceDataChild(nodeName, null)
338 if (targetNode === null) {
339 throw new ResponseException(BAD_REQUEST, "URI has bad format. \"" + nodeName + "\" was not found in parent data node.\n")
343 // Number of consumed elements
345 if (targetNode instanceof ListSchemaNode) {
346 val listNode = targetNode as ListSchemaNode;
347 val keysSize = listNode.keyDefinition.size
349 // every key has to be filled
350 if ((strings.length - consumed) < keysSize) {
351 throw new ResponseException(BAD_REQUEST,"Missing key for list \"" + listNode.QName.localName + "\".")
353 val uriKeyValues = strings.subList(consumed, consumed + keysSize);
354 val keyValues = new HashMap<QName, Object>();
356 for (key : listNode.keyDefinition) {
357 val uriKeyValue = uriKeyValues.get(i);
359 // key value cannot be NULL
360 if (uriKeyValue.equals(NULL_VALUE)) {
361 throw new ResponseException(BAD_REQUEST, "URI has bad format. List \"" + listNode.QName.localName
362 + "\" cannot contain \"null\" value as a key."
365 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
368 consumed = consumed + i;
369 builder.nodeWithKey(targetNode.QName, keyValues);
372 // Only one instance of node is allowed
373 builder.node(targetNode.QName);
375 if (targetNode instanceof DataNodeContainer) {
376 val remaining = strings.subList(consumed, strings.length);
377 val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer, mountPoint);
381 return new InstanceIdWithSchemaNode(builder.toInstance, targetNode, mountPoint)
384 def DataSchemaNode findInstanceDataChild(DataNodeContainer container, String name, URI moduleNamespace) {
385 var DataSchemaNode potentialNode = null
386 if (moduleNamespace === null) {
387 potentialNode = container.getDataChildByName(name);
389 potentialNode = container.childNodes.filter[n|n.QName.localName == name && n.QName.namespace == moduleNamespace].head
392 if (potentialNode.instantiatedDataSchema) {
393 return potentialNode;
395 val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
396 for (caze : allCases) {
397 potentialNode = caze.findInstanceDataChild(name, moduleNamespace);
398 if (potentialNode !== null) {
399 return potentialNode;
405 static def boolean isInstantiatedDataSchema(DataSchemaNode node) {
407 LeafSchemaNode: return true
408 LeafListSchemaNode: return true
409 ContainerSchemaNode: return true
410 ListSchemaNode: return true
411 default: return false
415 private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
416 checkNotNull(uriValue);
417 checkArgument(node instanceof LeafSchemaNode);
418 val urlDecoded = URLDecoder.decode(uriValue);
419 val typedef = (node as LeafSchemaNode).type;
421 var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
422 if(decoded === null) {
423 var baseType = RestUtil.resolveBaseTypeFrom(typedef)
424 if(baseType instanceof IdentityrefTypeDefinition) {
425 decoded = toQName(urlDecoded)
428 map.put(node.QName, decoded);
431 private static def String toModuleName(String str) {
433 if (str.contains(":")) {
434 val args = str.split(":");
435 if (args.size === 2) {
442 private def String toNodeName(String str) {
443 if (str.contains(":")) {
444 val args = str.split(":");
445 if (args.size === 2) {
452 private def QName toQName(String name) {
453 val module = name.toModuleName;
454 val node = name.toNodeName;
455 val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
456 .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
458 return QName.create(namespace,node);
461 def getRpcDefinition(String name) {
462 return qnameToRpc.get(name.toQName)
465 override onGlobalContextUpdated(SchemaContext context) {
466 this.globalSchema = context;
467 for (operation : context.operations) {
468 val qname = operation.QName;
469 qnameToRpc.put(qname, operation);