ArpHandler to ignore ip packet sent to default GW
[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 javax.ws.rs.core.Response
14 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener
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.LeafSchemaNode
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
31 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext
33 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
34 import org.slf4j.LoggerFactory
35
36 import static com.google.common.base.Preconditions.*
37 import org.opendaylight.controller.sal.core.api.mount.MountService
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
39
40 class ControllerContext implements SchemaServiceListener {
41     val static LOG = LoggerFactory.getLogger(ControllerContext)
42     val static ControllerContext INSTANCE = new ControllerContext
43     val static NULL_VALUE = "null"
44
45     @Property
46     var SchemaContext globalSchema;
47     
48     @Property
49     var MountService mountService;
50
51     private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
52     private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
53     private val Map<QName, RpcDefinition> qnameToRpc = new ConcurrentHashMap();
54
55     private new() {
56         if (INSTANCE !== null) {
57             throw new IllegalStateException("Already instantiated");
58         }
59     }
60
61     static def getInstance() {
62         return INSTANCE
63     }
64
65     private def void checkPreconditions() {
66         if (globalSchema === null) {
67             throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
68         }
69     }
70
71     def setSchemas(SchemaContext schemas) {
72         onGlobalContextUpdated(schemas)
73     }
74
75     public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
76         val ret = InstanceIdentifier.builder();
77         val pathArgs = restconfInstance.split("/");
78         if (pathArgs.empty) {
79             return null;
80         }
81         if (pathArgs.head.empty) {
82             pathArgs.remove(0)
83         }
84         val schemaNode = ret.collectPathArguments(pathArgs, globalSchema.findModule(pathArgs.head));
85         if (schemaNode === null) {
86             return null
87         }
88         return new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
89     }
90
91     private static def findModule(SchemaContext context,String argument) {
92         //checkPreconditions
93         checkNotNull(argument);
94         val startModule = argument.toModuleName();
95         return context.getLatestModule(startModule)
96     }
97
98     static def getLatestModule(SchemaContext schema,String moduleName) {
99         checkArgument(schema != null);
100         checkArgument(moduleName !== null && !moduleName.empty)
101         val modules = schema.modules.filter[m|m.name == moduleName]
102         var latestModule = modules.head
103         for (module : modules) {
104             if (module.revision.after(latestModule.revision)) {
105                 latestModule = module
106             }
107         }
108         return latestModule
109     }
110
111     def String toFullRestconfIdentifier(InstanceIdentifier path) {
112         checkPreconditions
113         val elements = path.path;
114         val ret = new StringBuilder();
115         val startQName = elements.get(0).nodeType;
116         val initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
117         var node = initialModule as DataSchemaNode;
118         for (element : elements) {
119             node = node.childByQName(element.nodeType);
120             ret.append(element.toRestconfIdentifier(node));
121         }
122         return ret.toString
123     }
124
125     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
126         '''/«argument.nodeType.toRestconfIdentifier()»'''
127     }
128
129     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
130         val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
131         val keyValues = argument.keyValues;
132         return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
133     }
134
135     private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
136         throw new IllegalArgumentException("Conversion of generic path argument is not supported");
137     }
138
139     def findModuleByNamespace(URI namespace) {
140         checkPreconditions
141         var module = uriToModuleName.get(namespace)
142         if (module === null) {
143             val moduleSchemas = globalSchema.findModuleByNamespace(namespace);
144             if(moduleSchemas === null) return null
145             var latestModule = moduleSchemas.head
146             for (m : moduleSchemas) {
147                 if (m.revision.after(latestModule.revision)) {
148                     latestModule = m
149                 }
150             }
151             if(latestModule === null) return null
152             uriToModuleName.put(namespace, latestModule.name)
153             module = latestModule.name;
154         }
155         return module
156     }
157
158     def findNamespaceByModule(String module) {
159         var namespace = moduleNameToUri.get(module)
160         if (namespace === null) {
161             val moduleSchemas = globalSchema.modules.filter[it|it.name.equals(module)]
162             var latestModule = moduleSchemas.head
163             for (m : moduleSchemas) {
164                 if (m.revision.after(latestModule.revision)) {
165                     latestModule = m
166                 }
167             }
168             if(latestModule === null) return null
169             namespace = latestModule.namespace
170             uriToModuleName.put(namespace, latestModule.name)
171         }
172         return namespace
173     }
174
175     def CharSequence toRestconfIdentifier(QName qname) {
176         checkPreconditions
177         var module = uriToModuleName.get(qname.namespace)
178         if (module === null) {
179             val moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
180             if(moduleSchema === null) throw new IllegalArgumentException()
181             uriToModuleName.put(qname.namespace, moduleSchema.name)
182             module = moduleSchema.name;
183         }
184         return '''«module»:«qname.localName»''';
185     }
186
187     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
188         for (caze : container.cases) {
189             val ret = caze.childByQName(name)
190             if (ret !== null) {
191                 return ret;
192             }
193         }
194         return null;
195     }
196
197     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
198         val ret = container.getDataChildByName(name);
199         return ret;
200     }
201
202     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
203         return container.dataNodeChildByQName(name);
204     }
205
206     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
207         return container.dataNodeChildByQName(name);
208     }
209
210     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
211         return null;
212     }
213
214     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
215         var ret = container.getDataChildByName(name);
216         if (ret === null) {
217
218             // Find in Choice Cases
219             for (node : container.childNodes) {
220                 if (node instanceof ChoiceCaseNode) {
221                     val caseNode = (node as ChoiceCaseNode);
222                     ret = caseNode.childByQName(name);
223                     if (ret !== null) {
224                         return ret;
225                     }
226                 }
227             }
228         }
229         return ret;
230     }
231
232     private def toUriString(Object object) {
233         if(object === null) return "";
234         return URLEncoder.encode(object.toString)
235     }
236
237     private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
238         DataNodeContainer parentNode) {
239         checkNotNull(strings)
240         if (parentNode === null) {
241             return null;
242         }
243         if (strings.empty) {
244             return parentNode as DataSchemaNode;
245         }
246         val nodeRef = strings.head;
247
248         val nodeName = nodeRef.toNodeName;
249         var targetNode = parentNode.findInstanceDataChild(nodeName);
250         if (targetNode instanceof ChoiceNode) {
251             return null
252         }
253         
254         if (targetNode === null) {
255             // Node is possibly in other mount point
256             val partialPath = builder.toInstance;
257             val mountPointSchema = mountService?.getMountPoint(partialPath)?.schemaContext;
258             if(mountPointSchema != null) {
259                 return builder.collectPathArguments(strings, mountPointSchema.findModule(strings.head));
260             }
261             return null
262         }
263         
264
265         // Number of consumed elements
266         var consumed = 1;
267         if (targetNode instanceof ListSchemaNode) {
268             val listNode = targetNode as ListSchemaNode;
269             val keysSize = listNode.keyDefinition.size
270
271             // every key has to be filled
272             if ((strings.length - consumed) < keysSize) {
273                 return null;
274             }
275             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
276             val keyValues = new HashMap<QName, Object>();
277             var i = 0;
278             for (key : listNode.keyDefinition) {
279                 val uriKeyValue = uriKeyValues.get(i);
280
281                 // key value cannot be NULL
282                 if (uriKeyValue.equals(NULL_VALUE)) {
283                     return null
284                 }
285                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
286                 i = i + 1;
287             }
288             consumed = consumed + i;
289             builder.nodeWithKey(targetNode.QName, keyValues);
290         } else {
291
292             // Only one instance of node is allowed
293             builder.node(targetNode.QName);
294         }
295         if (targetNode instanceof DataNodeContainer) {
296             val remaining = strings.subList(consumed, strings.length);
297             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
298             return result
299         }
300
301         return targetNode
302     }
303     
304     static def DataSchemaNode findInstanceDataChild(DataNodeContainer container, String name) {
305         // FIXME: Add namespace comparison
306         var potentialNode = container.getDataChildByName(name);
307         if(potentialNode.instantiatedDataSchema) {
308             return potentialNode;
309         }
310         val allCases = container.childNodes.filter(ChoiceNode).map[cases].flatten
311         for (caze : allCases) {
312             potentialNode = caze.findInstanceDataChild(name);
313             if(potentialNode != null) {
314                 return potentialNode;
315             }
316         }
317         return null;
318     }
319     
320     static def boolean isInstantiatedDataSchema(DataSchemaNode node) {
321         switch node {
322             LeafSchemaNode: return true
323             LeafListSchemaNode: return true
324             ContainerSchemaNode: return true
325             ListSchemaNode: return true
326             default: return false
327         }
328     }
329
330     private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
331         checkNotNull(uriValue);
332         checkArgument(node instanceof LeafSchemaNode);
333         val urlDecoded = URLDecoder.decode(uriValue);
334         val typedef = (node as LeafSchemaNode).type;
335         
336         var decoded = TypeDefinitionAwareCodec.from(typedef)?.deserialize(urlDecoded)
337         if(decoded === null) {
338             var baseType = RestUtil.resolveBaseTypeFrom(typedef)
339             if(baseType instanceof IdentityrefTypeDefinition) {
340                 decoded = toQName(urlDecoded)
341             }
342         }
343         map.put(node.QName, decoded);
344     }
345
346     private static def String toModuleName(String str) {
347         checkNotNull(str)
348         if (str.contains(":")) {
349             val args = str.split(":");
350             checkArgument(args.size === 2);
351             return args.get(0);
352         } else {
353             return null;
354         }
355     }
356
357     private def String toNodeName(String str) {
358         if (str.contains(":")) {
359             val args = str.split(":");
360             checkArgument(args.size === 2);
361             return args.get(1);
362         } else {
363             return str;
364         }
365     }
366
367     private def QName toQName(String name) {
368         val module = name.toModuleName;
369         val node = name.toNodeName;
370         val namespace = FluentIterable.from(globalSchema.modules.sort[o1,o2 | o1.revision.compareTo(o2.revision)]) //
371             .transform[QName.create(namespace,revision,it.name)].findFirst[module == localName]
372         ;
373         return QName.create(namespace,node);
374     }
375
376     def getRpcDefinition(String name) {
377         return qnameToRpc.get(name.toQName)
378     }
379
380     override onGlobalContextUpdated(SchemaContext context) {
381         this.globalSchema = context;
382         for (operation : context.operations) {
383             val qname = operation.QName;
384             qnameToRpc.put(qname, operation);
385         }
386     }
387
388 }