Merge "Improve client logging"
[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.yangtools.yang.model.api.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     public 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         checkArgument(namespace !== null)
133         val moduleSchemas = globalSchema.findModuleByNamespace(namespace)
134         return moduleSchemas?.filterLatestModule
135     }
136
137     def findModuleByNamespace(MountInstance mountPoint, URI namespace) {
138         checkArgument(namespace !== null && mountPoint !== null)
139         val mountPointSchema = mountPoint.schemaContext;
140         val moduleSchemas = mountPointSchema?.findModuleByNamespace(namespace)
141         return moduleSchemas?.filterLatestModule
142     }
143
144     def String toFullRestconfIdentifier(InstanceIdentifier path) {
145         checkPreconditions
146         val elements = path.path;
147         val ret = new StringBuilder();
148         val startQName = elements.get(0).nodeType;
149         val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
150         var node = initialModule as DataSchemaNode;
151         for (element : elements) {
152             node = node.childByQName(element.nodeType);
153             ret.append(element.toRestconfIdentifier(node));
154         }
155         return ret.toString
156     }
157
158     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
159         '''/«argument.nodeType.toRestconfIdentifier()»'''
160     }
161
162     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
163         val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
164         val keyValues = argument.keyValues;
165         return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
166     }
167
168     private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
169         throw new IllegalArgumentException("Conversion of generic path argument is not supported");
170     }
171
172     def findModuleNameByNamespace(URI namespace) {
173         checkPreconditions
174         var moduleName = uriToModuleName.get(namespace)
175         if (moduleName === null) {
176             val module = findModuleByNamespace(namespace)
177             if (module === null) return null
178             moduleName = module.name
179             uriToModuleName.put(namespace, moduleName)
180         }
181         return moduleName
182     }
183
184     def findModuleNameByNamespace(MountInstance mountPoint, URI namespace) {
185         val module = mountPoint.findModuleByNamespace(namespace);
186         return module?.name
187     }
188
189     def findNamespaceByModuleName(String moduleName) {
190         var namespace = moduleNameToUri.get(moduleName)
191         if (namespace === null) {
192             var module = findModuleByName(moduleName)
193             if(module === null) return null
194             namespace = module.namespace
195             uriToModuleName.put(namespace, moduleName)
196         }
197         return namespace
198     }
199
200     def findNamespaceByModuleName(MountInstance mountPoint, String moduleName) {
201         val module = mountPoint.findModuleByName(moduleName)
202         return module?.namespace
203     }
204
205     def CharSequence toRestconfIdentifier(QName qname) {
206         checkPreconditions
207         var module = uriToModuleName.get(qname.namespace)
208         if (module === null) {
209             val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
210             if(moduleSchema === null) throw new IllegalArgumentException()
211             uriToModuleName.put(qname.namespace, moduleSchema.name)
212             module = moduleSchema.name;
213         }
214         return '''«module»:«qname.localName»''';
215     }
216
217     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
218         for (caze : container.cases) {
219             val ret = caze.childByQName(name)
220             if (ret !== null) {
221                 return ret;
222             }
223         }
224         return null;
225     }
226
227     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
228         val ret = container.getDataChildByName(name);
229         return ret;
230     }
231
232     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
233         return container.dataNodeChildByQName(name);
234     }
235
236     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
237         return container.dataNodeChildByQName(name);
238     }
239
240     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
241         return null;
242     }
243
244     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
245         var ret = container.getDataChildByName(name);
246         if (ret === null) {
247
248             // Find in Choice Cases
249             for (node : container.childNodes) {
250                 if (node instanceof ChoiceCaseNode) {
251                     val caseNode = (node as ChoiceCaseNode);
252                     ret = caseNode.childByQName(name);
253                     if (ret !== null) {
254                         return ret;
255                     }
256                 }
257             }
258         }
259         return ret;
260     }
261
262     private def toUriString(Object object) {
263         if(object === null) return "";
264         return URLEncoder.encode(object.toString)
265     }
266
267     private def InstanceIdWithSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
268         DataNodeContainer parentNode, MountInstance mountPoint) {
269         checkNotNull(strings)
270         if (parentNode === null) {
271             return null;
272         }
273         if (strings.empty) {
274             return new InstanceIdWithSchemaNode(builder.toInstance, parentNode as DataSchemaNode, mountPoint)
275         }
276
277         val nodeName = strings.head.toNodeName
278         val moduleName = strings.head.toModuleName
279         var DataSchemaNode targetNode = null
280         if (!moduleName.nullOrEmpty) {
281             // if it is mount point
282             if (moduleName == MOUNT_MODULE && nodeName == MOUNT_NODE) {
283                 if (mountPoint !== null) {
284                     throw new ResponseException(BAD_REQUEST, "Restconf supports just one mount point in URI.")
285                 }
286
287                 if (mountService === null) {
288                     throw new ResponseException(SERVICE_UNAVAILABLE, "MountService was not found. "
289                         + "Finding behind mount points does not work."
290                     )
291                 }
292
293                 val partialPath = builder.toInstance;
294                 val mount = mountService.getMountPoint(partialPath)
295                 if (mount === null) {
296                     LOG.debug("Instance identifier to missing mount point: {}", partialPath)
297                     throw new ResponseException(BAD_REQUEST, "Mount point does not exist.")
298                 }
299
300                 val mountPointSchema = mount.schemaContext;
301                 if (mountPointSchema === null) {
302                     throw new ResponseException(BAD_REQUEST, "Mount point does not contain any schema with modules.")
303                 }
304
305                 if (strings.size == 1) { // any data node is not behind mount point
306                     return new InstanceIdWithSchemaNode(InstanceIdentifier.builder().toInstance, mountPointSchema, mount)
307                 }
308
309                 val moduleNameBehindMountPoint = strings.get(1).toModuleName()
310                 if (moduleNameBehindMountPoint === null) {
311                     throw new ResponseException(BAD_REQUEST,
312                         "First node after mount point in URI has to be in format \"moduleName:nodeName\"")
313                 }
314
315                 val moduleBehindMountPoint = mountPointSchema.getLatestModule(moduleNameBehindMountPoint)
316                 if (moduleBehindMountPoint === null) {
317                     throw new ResponseException(BAD_REQUEST,
318                         "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
319                 }
320
321                 return collectPathArguments(InstanceIdentifier.builder(), strings.subList(1, strings.size),
322                     moduleBehindMountPoint, mount);
323             }
324
325             var Module module = null;
326             if (mountPoint === null) {
327                 module = globalSchema.getLatestModule(moduleName)
328                 if (module === null) {
329                     throw new ResponseException(BAD_REQUEST,
330                         "URI has bad format. \"" + moduleName + "\" module does not exist.")
331                 }
332             } else {
333                 module = mountPoint.schemaContext?.getLatestModule(moduleName)
334                 if (module === null) {
335                     throw new ResponseException(BAD_REQUEST,
336                         "URI has bad format. \"" + moduleName + "\" module does not exist in mount point.")
337                 }
338             }
339             targetNode = parentNode.findInstanceDataChild(nodeName, module.namespace)
340             if (targetNode === null) {
341                 throw new ResponseException(BAD_REQUEST, "URI has bad format. Possible reasons:\n" +
342                     "1. \"" + strings.head + "\" was not found in parent data node.\n" +
343                     "2. \"" + strings.head + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + strings.head + "\".")
344             }
345         } else { // string without module name
346             targetNode = parentNode.findInstanceDataChild(nodeName, null)
347             if (targetNode === null) {
348                 throw new ResponseException(BAD_REQUEST, "URI has bad format. \"" + nodeName + "\" was not found in parent data node.\n")
349             }
350         }
351
352         // Number of consumed elements
353         var consumed = 1;
354         if (targetNode instanceof ListSchemaNode) {
355             val listNode = targetNode as ListSchemaNode;
356             val keysSize = listNode.keyDefinition.size
357
358             // every key has to be filled
359             if ((strings.length - consumed) < keysSize) {
360                 throw new ResponseException(BAD_REQUEST,"Missing key for list \"" + listNode.QName.localName + "\".")
361             }
362             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
363             val keyValues = new HashMap<QName, Object>();
364             var i = 0;
365             for (key : listNode.keyDefinition) {
366                 val uriKeyValue = uriKeyValues.get(i);
367
368                 // key value cannot be NULL
369                 if (uriKeyValue.equals(NULL_VALUE)) {
370                     throw new ResponseException(BAD_REQUEST, "URI has bad format. List \"" + listNode.QName.localName
371                         + "\" cannot contain \"null\" value as a key."
372                     )
373                 }
374                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
375                 i = i + 1;
376             }
377             consumed = consumed + i;
378             builder.nodeWithKey(targetNode.QName, keyValues);
379         } else {
380
381             // Only one instance of node is allowed
382             builder.node(targetNode.QName);
383         }
384         if (targetNode instanceof DataNodeContainer) {
385             val remaining = strings.subList(consumed, strings.length);
386             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer, mountPoint);
387             return result
388         }
389
390         return new InstanceIdWithSchemaNode(builder.toInstance, targetNode, mountPoint)
391     }
392
393     def DataSchemaNode findInstanceDataChild(DataNodeContainer container, String name, URI moduleNamespace) {
394         var DataSchemaNode potentialNode = null
395         if (moduleNamespace === null) {
396             potentialNode = container.getDataChildByName(name);
397         } else {
398             potentialNode = container.childNodes.filter[n|n.QName.localName == name && n.QName.namespace == moduleNamespace].head
399         }
400
401         if (potentialNode.instantiatedDataSchema) {
402             return potentialNode;
403         }
404         val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
405         for (caze : allCases) {
406             potentialNode = caze.findInstanceDataChild(name, moduleNamespace);
407             if (potentialNode !== null) {
408                 return potentialNode;
409             }
410         }
411         return null;
412     }
413
414     static def boolean isInstantiatedDataSchema(DataSchemaNode node) {
415         switch node {
416             LeafSchemaNode: return true
417             LeafListSchemaNode: return true
418             ContainerSchemaNode: return true
419             ListSchemaNode: return true
420             default: return false
421         }
422     }
423
424     private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
425         checkNotNull(uriValue);
426         checkArgument(node instanceof LeafSchemaNode);
427         val urlDecoded = URLDecoder.decode(uriValue);
428         val typedef = (node as LeafSchemaNode).type;
429
430         var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
431         if(decoded === null) {
432             var baseType = RestUtil.resolveBaseTypeFrom(typedef)
433             if(baseType instanceof IdentityrefTypeDefinition) {
434                 decoded = toQName(urlDecoded)
435             }
436         }
437         map.put(node.QName, decoded);
438     }
439
440     private static def String toModuleName(String str) {
441         checkNotNull(str)
442         if (str.contains(":")) {
443             val args = str.split(":");
444             if (args.size === 2) {
445                 return args.get(0);
446             }
447         }
448         return null;
449     }
450
451     private def String toNodeName(String str) {
452         if (str.contains(":")) {
453             val args = str.split(":");
454             if (args.size === 2) {
455                 return args.get(1);
456             }
457         }
458         return str;
459     }
460
461     private def QName toQName(String name) {
462         val module = name.toModuleName;
463         val node = name.toNodeName;
464         val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
465             .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
466         ;
467         return QName.create(namespace,node);
468     }
469
470     def getRpcDefinition(String name) {
471         return qnameToRpc.get(name.toQName)
472     }
473
474     override onGlobalContextUpdated(SchemaContext context) {
475         this.globalSchema = context;
476         for (operation : context.operations) {
477             val qname = operation.QName;
478             qnameToRpc.put(qname, operation);
479         }
480     }
481
482 }