Merge "Fix for Bug 3"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / ControllerContext.xtend
1 package org.opendaylight.controller.sal.restconf.impl
2
3 import com.google.common.collect.BiMap
4 import com.google.common.collect.FluentIterable
5 import com.google.common.collect.HashBiMap
6 import java.net.URI
7 import java.net.URLDecoder
8 import java.net.URLEncoder
9 import java.util.HashMap
10 import java.util.List
11 import java.util.Map
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
37
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
41
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"
49
50     @Property
51     var SchemaContext globalSchema;
52     
53     @Property
54     var MountService mountService;
55
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();
59
60     private new() {
61         if (INSTANCE !== null) {
62             throw new IllegalStateException("Already instantiated");
63         }
64     }
65
66     static def getInstance() {
67         return INSTANCE
68     }
69
70     private def void checkPreconditions() {
71         if (globalSchema === null) {
72             throw new ResponseException(SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
73         }
74     }
75
76     def setSchemas(SchemaContext schemas) {
77         onGlobalContextUpdated(schemas)
78     }
79
80     public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
81         checkPreconditions
82         val pathArgs = restconfInstance.split("/");
83         if (pathArgs.empty) {
84             return null;
85         }
86         if (pathArgs.head.empty) {
87             pathArgs.remove(0)
88         }
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\"")
92         }
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")
97         }
98         return iiWithSchemaNode
99     }
100
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
106     }
107     
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
113             }
114         }
115         return latestModule
116     }
117     
118     def findModuleByName(String moduleName) {
119         checkPreconditions
120         checkArgument(moduleName !== null && !moduleName.empty)
121         return globalSchema.getLatestModule(moduleName)
122     }
123     
124     def findModuleByName(MountInstance mountPoint, String moduleName) {
125         checkArgument(moduleName !== null && mountPoint !== null)
126         val mountPointSchema = mountPoint.schemaContext;
127         return mountPointSchema?.getLatestModule(moduleName);
128     }
129     
130     def findModuleByNamespace(URI namespace) {
131         checkPreconditions
132         val moduleSchemas = globalSchema.findModuleByNamespace(namespace)
133         return moduleSchemas?.filterLatestModule
134     }
135     
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
141     }
142
143     def String toFullRestconfIdentifier(InstanceIdentifier path) {
144         checkPreconditions
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));
153         }
154         return ret.toString
155     }
156
157     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
158         '''/«argument.nodeType.toRestconfIdentifier()»'''
159     }
160
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»'''
165     }
166
167     private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
168         throw new IllegalArgumentException("Conversion of generic path argument is not supported");
169     }
170
171     def findModuleNameByNamespace(URI namespace) {
172         checkPreconditions
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;
181         }
182         return module
183     }
184
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)
192         }
193         return namespace
194     }
195
196     def CharSequence toRestconfIdentifier(QName qname) {
197         checkPreconditions
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;
204         }
205         return '''«module»:«qname.localName»''';
206     }
207
208     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
209         for (caze : container.cases) {
210             val ret = caze.childByQName(name)
211             if (ret !== null) {
212                 return ret;
213             }
214         }
215         return null;
216     }
217
218     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
219         val ret = container.getDataChildByName(name);
220         return ret;
221     }
222
223     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
224         return container.dataNodeChildByQName(name);
225     }
226
227     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
228         return container.dataNodeChildByQName(name);
229     }
230
231     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
232         return null;
233     }
234
235     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
236         var ret = container.getDataChildByName(name);
237         if (ret === null) {
238
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);
244                     if (ret !== null) {
245                         return ret;
246                     }
247                 }
248             }
249         }
250         return ret;
251     }
252
253     private def toUriString(Object object) {
254         if(object === null) return "";
255         return URLEncoder.encode(object.toString)
256     }
257     
258     private def InstanceIdWithSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
259         DataNodeContainer parentNode, MountInstance mountPoint) {
260         checkNotNull(strings)
261         if (parentNode === null) {
262             return null;
263         }
264         if (strings.empty) {
265             return new InstanceIdWithSchemaNode(builder.toInstance, parentNode as DataSchemaNode, mountPoint)
266         }
267         
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.")
276                 }
277                 
278                 if (mountService === null) {
279                     throw new ResponseException(SERVICE_UNAVAILABLE, "MountService was not found. " 
280                         + "Finding behind mount points does not work."
281                     )
282                 }
283                 
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.")
289                 }
290                 
291                 val mountPointSchema = mount.schemaContext;
292                 if (mountPointSchema === null) {
293                     throw new ResponseException(BAD_REQUEST, "Mount point does not contain any schema with modules.")
294                 }
295                 
296                 if (strings.size == 1) { // any data node is not behind mount point
297                     return new InstanceIdWithSchemaNode(InstanceIdentifier.builder().toInstance, mountPointSchema, mount)
298                 }
299                 
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\"")
304                 }
305                 
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.")
310                 }
311                 
312                 return collectPathArguments(InstanceIdentifier.builder(), strings.subList(1, strings.size),
313                     moduleBehindMountPoint, mount);
314             }
315             
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.")
322                 }
323             } else {
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.")
328                 }
329             }
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 + "\".")
335             }
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")
340             }
341         }
342         
343         // Number of consumed elements
344         var consumed = 1;
345         if (targetNode instanceof ListSchemaNode) {
346             val listNode = targetNode as ListSchemaNode;
347             val keysSize = listNode.keyDefinition.size
348
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 + "\".")
352             }
353             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
354             val keyValues = new HashMap<QName, Object>();
355             var i = 0;
356             for (key : listNode.keyDefinition) {
357                 val uriKeyValue = uriKeyValues.get(i);
358
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."
363                     )
364                 }
365                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
366                 i = i + 1;
367             }
368             consumed = consumed + i;
369             builder.nodeWithKey(targetNode.QName, keyValues);
370         } else {
371
372             // Only one instance of node is allowed
373             builder.node(targetNode.QName);
374         }
375         if (targetNode instanceof DataNodeContainer) {
376             val remaining = strings.subList(consumed, strings.length);
377             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer, mountPoint);
378             return result
379         }
380
381         return new InstanceIdWithSchemaNode(builder.toInstance, targetNode, mountPoint)
382     }
383
384     def DataSchemaNode findInstanceDataChild(DataNodeContainer container, String name, URI moduleNamespace) {
385         var DataSchemaNode potentialNode = null
386         if (moduleNamespace === null) {
387             potentialNode = container.getDataChildByName(name);
388         } else {
389             potentialNode = container.childNodes.filter[n|n.QName.localName == name && n.QName.namespace == moduleNamespace].head
390         }
391         
392         if (potentialNode.instantiatedDataSchema) {
393             return potentialNode;
394         }
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;
400             }
401         }
402         return null;
403     }
404     
405     static def boolean isInstantiatedDataSchema(DataSchemaNode node) {
406         switch node {
407             LeafSchemaNode: return true
408             LeafListSchemaNode: return true
409             ContainerSchemaNode: return true
410             ListSchemaNode: return true
411             default: return false
412         }
413     }
414
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;
420         
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)
426             }
427         }
428         map.put(node.QName, decoded);
429     }
430
431     private static def String toModuleName(String str) {
432         checkNotNull(str)
433         if (str.contains(":")) {
434             val args = str.split(":");
435             if (args.size === 2) {
436                 return args.get(0);
437             }
438         }
439         return null;
440     }
441
442     private def String toNodeName(String str) {
443         if (str.contains(":")) {
444             val args = str.split(":");
445             if (args.size === 2) {
446                 return args.get(1);
447             }
448         }
449         return str;
450     }
451
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]
457         ;
458         return QName.create(namespace,node);
459     }
460
461     def getRpcDefinition(String name) {
462         return qnameToRpc.get(name.toQName)
463     }
464
465     override onGlobalContextUpdated(SchemaContext context) {
466         this.globalSchema = context;
467         for (operation : context.operations) {
468             val qname = operation.QName;
469             qnameToRpc.put(qname, operation);
470         }
471     }
472
473 }