Merge "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 / RestconfImpl.xtend
1 package org.opendaylight.controller.sal.restconf.impl
2
3 import java.util.ArrayList
4 import java.util.HashMap
5 import java.util.List
6 import java.util.Set
7 import javax.ws.rs.core.Response
8 import org.opendaylight.controller.md.sal.common.api.TransactionStatus
9 import org.opendaylight.controller.sal.rest.api.RestconfService
10 import org.opendaylight.yangtools.yang.common.QName
11 import org.opendaylight.yangtools.yang.data.api.CompositeNode
12 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
13 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
14 import org.opendaylight.yangtools.yang.data.api.Node
15 import org.opendaylight.yangtools.yang.data.impl.NodeFactory
16 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
17 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
18 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
19 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
20 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
21 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
22 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
23 import org.opendaylight.yangtools.yang.model.api.Module
24 import org.opendaylight.yangtools.yang.model.api.TypeDefinition
25 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
26
27 import static javax.ws.rs.core.Response.Status.*
28 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
29
30 class RestconfImpl implements RestconfService {
31
32     val static RestconfImpl INSTANCE = new RestconfImpl
33
34     @Property
35     BrokerFacade broker
36
37     @Property
38     extension ControllerContext controllerContext
39
40     private new() {
41         if (INSTANCE !== null) {
42             throw new IllegalStateException("Already instantiated");
43         }
44     }
45
46     static def getInstance() {
47         return INSTANCE
48     }
49
50     override readAllData() {
51 //        return broker.readOperationalData("".toInstanceIdentifier.getInstanceIdentifier);
52         throw new UnsupportedOperationException("Reading all data is currently not supported.")
53     }
54
55     override getModules() {
56         throw new UnsupportedOperationException("TODO: auto-generated method stub")
57     }
58
59     override getRoot() {
60         return null;
61     }
62
63     override invokeRpc(String identifier, CompositeNode payload) {
64         return callRpc(identifier.rpcDefinition, payload)
65     }
66     
67     override invokeRpc(String identifier) {
68         return callRpc(identifier.rpcDefinition, null)
69     }
70     
71     private def StructuredData callRpc(RpcDefinition rpc, CompositeNode payload) {
72         if (rpc === null) {
73             throw new ResponseException(NOT_FOUND, "RPC does not exist.");
74         }
75         var CompositeNode rpcRequest;
76         if (payload === null) {
77             rpcRequest = NodeFactory.createMutableCompositeNode(rpc.QName, null, null, null, null)
78         } else {
79             val value = normalizeNode(payload, rpc.input, null)
80             val List<Node<?>> input = new ArrayList
81             input.add(value)
82             rpcRequest = NodeFactory.createMutableCompositeNode(rpc.QName, null, input, null, null)
83         }
84         val rpcResult = broker.invokeRpc(rpc.QName, rpcRequest);
85         if (!rpcResult.successful) {
86             throw new ResponseException(INTERNAL_SERVER_ERROR, "Operation failed")
87         }
88         if (rpcResult.result === null) {
89             return null
90         }
91         return new StructuredData(rpcResult.result, rpc.output)
92     }
93
94     override readData(String identifier) {
95         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
96         val data = broker.readOperationalData(instanceIdentifierWithSchemaNode.getInstanceIdentifier);
97         return new StructuredData(data, instanceIdentifierWithSchemaNode.schemaNode)
98     }
99
100     override readConfigurationData(String identifier) {
101         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
102         val data = broker.readConfigurationData(instanceIdentifierWithSchemaNode.getInstanceIdentifier);
103         return new StructuredData(data, instanceIdentifierWithSchemaNode.schemaNode)
104     }
105
106     override readOperationalData(String identifier) {
107         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
108         val data = broker.readOperationalData(instanceIdentifierWithSchemaNode.getInstanceIdentifier);
109         return new StructuredData(data, instanceIdentifierWithSchemaNode.schemaNode)
110     }
111
112     override updateConfigurationDataLegacy(String identifier, CompositeNode payload) {
113         updateConfigurationData(identifier, payload);
114     }
115
116     override updateConfigurationData(String identifier, CompositeNode payload) {
117         val identifierWithSchemaNode = identifier.resolveInstanceIdentifier
118         val value = normalizeNode(payload, identifierWithSchemaNode.schemaNode, identifierWithSchemaNode.mountPoint)
119         val status = broker.commitConfigurationDataPut(identifierWithSchemaNode.instanceIdentifier, value).get();
120         switch status.result {
121             case TransactionStatus.COMMITED: Response.status(OK).build
122             default: Response.status(INTERNAL_SERVER_ERROR).build
123         }
124     }
125
126     override createConfigurationDataLegacy(String identifier, CompositeNode payload) {
127         createConfigurationData(identifier, payload);
128     }
129
130     override createConfigurationData(String identifier, CompositeNode payload) {
131         val uncompleteIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
132         var schemaNode = (uncompleteIdentifierWithSchemaNode.schemaNode as DataNodeContainer).getSchemaChildNode(payload)
133         if (schemaNode === null) {
134             schemaNode = payload.findModule(uncompleteIdentifierWithSchemaNode.instanceIdentifier)?.getSchemaChildNode(payload)
135         }
136         val value = normalizeNode(payload, schemaNode, uncompleteIdentifierWithSchemaNode.instanceIdentifier)
137         val completeIdentifierWithSchemaNode = uncompleteIdentifierWithSchemaNode.addLastIdentifierFromData(value, schemaNode)
138         val status = broker.commitConfigurationDataPost(completeIdentifierWithSchemaNode.instanceIdentifier, value)?.get();
139         if (status === null) {
140             return Response.status(ACCEPTED).build
141         }
142         switch status.result {
143             case TransactionStatus.COMMITED: Response.status(NO_CONTENT).build
144             default: Response.status(INTERNAL_SERVER_ERROR).build
145         }
146     }
147     
148     override createConfigurationData(CompositeNode payload) {
149         val schemaNode = payload.findModule(null)?.getSchemaChildNode(payload)
150         val value = normalizeNode(payload, schemaNode, null)
151         val identifierWithSchemaNode = addLastIdentifierFromData(null, value, schemaNode)
152         val status = broker.commitConfigurationDataPost(identifierWithSchemaNode.instanceIdentifier, value)?.get();
153         if (status === null) {
154             return Response.status(ACCEPTED).build
155         }
156         switch status.result {
157             case TransactionStatus.COMMITED: Response.status(NO_CONTENT).build
158             default: Response.status(INTERNAL_SERVER_ERROR).build
159         }
160     }
161     
162     override deleteConfigurationData(String identifier) {
163         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
164         val status = broker.commitConfigurationDataDelete(instanceIdentifierWithSchemaNode.getInstanceIdentifier).get;
165         switch status.result {
166             case TransactionStatus.COMMITED: Response.status(OK).build
167             default: Response.status(INTERNAL_SERVER_ERROR).build
168         }
169     }
170
171     private def InstanceIdWithSchemaNode resolveInstanceIdentifier(String identifier) {
172         val identifierWithSchemaNode = identifier.toInstanceIdentifier
173         if (identifierWithSchemaNode === null) {
174             throw new ResponseException(BAD_REQUEST, "URI has bad format");
175         }
176         return identifierWithSchemaNode
177     }
178
179     private def dispatch Module findModule(CompositeNode data, InstanceIdentifier partialPath) {
180         if (partialPath !== null && !partialPath.path.empty) {
181             return data.nodeType.namespace.findModuleByNamespace(partialPath)
182         } else {
183             return data.nodeType.namespace.findModuleByNamespace
184         }
185     }
186
187     private def dispatch Module findModule(CompositeNodeWrapper data, InstanceIdentifier partialPath) {
188         var Module module = null;
189         if (partialPath !== null && !partialPath.path.empty) {
190             module = data.namespace.findModuleByNamespace(partialPath) // namespace from XML
191             if (module === null) {
192                 module = data.namespace.toString.findModuleByName(partialPath) // namespace (module name) from JSON
193             }
194         } else {
195             module = data.namespace.findModuleByNamespace // namespace from XML
196             if (module === null) {
197                 module = data.namespace.toString.findModuleByName // namespace (module name) from JSON
198             }
199         }
200         return module
201     }
202     
203     private def dispatch DataSchemaNode getSchemaChildNode(DataNodeContainer parentSchemaNode, CompositeNode data) {
204         return parentSchemaNode?.getDataChildByName(data.nodeType.localName)
205     }
206     
207     private def dispatch DataSchemaNode getSchemaChildNode(DataNodeContainer parentSchemaNode, CompositeNodeWrapper data) {
208         return parentSchemaNode?.getDataChildByName(data.localName)
209     }
210
211     private def InstanceIdWithSchemaNode addLastIdentifierFromData(InstanceIdWithSchemaNode identifierWithSchemaNode, CompositeNode data, DataSchemaNode schemaOfData) {
212         val iiOriginal = identifierWithSchemaNode?.instanceIdentifier
213         var  InstanceIdentifierBuilder iiBuilder = null
214         if (iiOriginal === null) { 
215             iiBuilder = InstanceIdentifier.builder
216         } else {
217             iiBuilder = InstanceIdentifier.builder(iiOriginal)
218         }
219
220         if (schemaOfData instanceof ListSchemaNode) {
221             iiBuilder.nodeWithKey(schemaOfData.QName, (schemaOfData as ListSchemaNode).resolveKeysFromData(data))
222         } else {
223             iiBuilder.node(schemaOfData.QName)
224         }
225         return new InstanceIdWithSchemaNode(iiBuilder.toInstance, schemaOfData, identifierWithSchemaNode?.mountPoint)
226     }
227
228     private def resolveKeysFromData(ListSchemaNode listNode, CompositeNode dataNode) {
229         val keyValues = new HashMap<QName, Object>();
230         for (key : listNode.keyDefinition) {
231             val dataNodeKeyValueObject = dataNode.getSimpleNodesByName(key.localName)?.head?.value
232             if (dataNodeKeyValueObject === null) {
233                 throw new ResponseException(BAD_REQUEST, "Data contains list \"" + dataNode.nodeType.localName + "\" which does not contain key: \"" + key.localName + "\"")
234             }
235             keyValues.put(key, dataNodeKeyValueObject);
236         }
237         return keyValues
238     }
239
240     private def CompositeNode normalizeNode(CompositeNode node, DataSchemaNode schema, InstanceIdentifier mountPoint) {
241         if (schema !== null && !schema.containerOrList) {
242             throw new ResponseException(BAD_REQUEST, "Root element has to be container or list yang datatype.");
243         }
244         if (node instanceof CompositeNodeWrapper) {
245             if ((node  as CompositeNodeWrapper).changeAllowed) {
246                 normalizeNode(node as CompositeNodeWrapper, schema, null, mountPoint)
247             }
248             return (node as CompositeNodeWrapper).unwrap()
249         }
250         return node
251     }
252
253     private def isContainerOrList(DataSchemaNode schemaNode) {
254         return (schemaNode instanceof ContainerSchemaNode) || (schemaNode instanceof ListSchemaNode)
255     }
256
257     private def void normalizeNode(NodeWrapper<?> nodeBuilder, DataSchemaNode schema, QName previousAugment,
258         InstanceIdentifier mountPoint) {
259         if (schema === null) {
260             throw new ResponseException(BAD_REQUEST,
261                 "Data has bad format.\n\"" + nodeBuilder.localName + "\" does not exist in yang schema.");
262         }
263         var validQName = schema.QName
264         var currentAugment = previousAugment;
265         if (schema.augmenting) {
266             currentAugment = schema.QName
267         } else if (previousAugment !== null && schema.QName.namespace !== previousAugment.namespace) {
268             validQName = QName.create(currentAugment, schema.QName.localName);
269         }
270         var moduleName = controllerContext.findModuleNameByNamespace(validQName.namespace);
271         if (moduleName === null && mountPoint !== null && !mountPoint.path.empty) {
272             moduleName = controllerContext.findModuleByNamespace(validQName.namespace, mountPoint)?.name
273         }
274         if (nodeBuilder.namespace === null || nodeBuilder.namespace == validQName.namespace ||
275             nodeBuilder.namespace.toString == moduleName) {
276             nodeBuilder.qname = validQName
277         } else {
278             throw new ResponseException(BAD_REQUEST,
279                 "Data has bad format.\nIf data is in XML format then namespace for \"" + nodeBuilder.localName +
280                     "\" should be \"" + schema.QName.namespace + "\".\nIf data is in Json format then module name for \"" +
281                     nodeBuilder.localName + "\" should be \"" + moduleName + "\".");
282         }
283
284         if (nodeBuilder instanceof CompositeNodeWrapper) {
285             val List<NodeWrapper<?>> children = (nodeBuilder as CompositeNodeWrapper).getValues
286             for (child : children) {
287                 normalizeNode(child,
288                     findFirstSchemaByLocalName(child.localName, (schema as DataNodeContainer).childNodes),
289                     currentAugment, mountPoint)
290             }
291             if(schema instanceof ListSchemaNode) {
292                 val listKeys = (schema as ListSchemaNode).keyDefinition
293                 for (listKey : listKeys) {
294                     var foundKey = false
295                     for (child : children) {
296                         if (child.unwrap.nodeType.localName == listKey.localName) {
297                             foundKey = true;
298                         }
299                     }
300                     if (!foundKey) {
301                         throw new ResponseException(BAD_REQUEST,
302                             "Missing key in URI \"" + listKey.localName + "\" of list \"" + schema.QName.localName + "\"")
303                     }
304                 }
305             }
306         } else if (nodeBuilder instanceof SimpleNodeWrapper) {
307             val simpleNode = (nodeBuilder as SimpleNodeWrapper)
308             val value = simpleNode.value
309             var inputValue = value;
310             
311             if (schema.typeDefinition instanceof IdentityrefTypeDefinition) {
312                 if (value instanceof String) {
313                     inputValue = new IdentityValuesDTO(validQName.namespace.toString, value as String, null)
314                 } // else value is instance of ValuesDTO
315             }
316             
317             val outputValue = RestCodec.from(schema.typeDefinition)?.deserialize(inputValue);
318             simpleNode.setValue(outputValue)
319         } else if (nodeBuilder instanceof EmptyNodeWrapper) {
320             val emptyNodeBuilder = nodeBuilder as EmptyNodeWrapper
321             if (schema instanceof LeafSchemaNode) {
322                 emptyNodeBuilder.setComposite(false);
323             } else if (schema instanceof ContainerSchemaNode) {
324
325                 // FIXME: Add presence check
326                 emptyNodeBuilder.setComposite(true);
327             }
328         }
329     }
330
331     private def dispatch TypeDefinition<?> typeDefinition(LeafSchemaNode node) {
332         var baseType = node.type
333         while (baseType.baseType !== null) {
334             baseType = baseType.baseType;
335         }
336         baseType
337     }
338
339     private def dispatch TypeDefinition<?> typeDefinition(LeafListSchemaNode node) {
340         var TypeDefinition<?> baseType = node.type
341         while (baseType.baseType !== null) {
342             baseType = baseType.baseType;
343         }
344         baseType
345     }
346
347     private def DataSchemaNode findFirstSchemaByLocalName(String localName, Set<DataSchemaNode> schemas) {
348         for (schema : schemas) {
349             if (schema instanceof ChoiceNode) {
350                 for (caze : (schema as ChoiceNode).cases) {
351                     val result = findFirstSchemaByLocalName(localName, caze.childNodes)
352                     if (result !== null) {
353                         return result
354                     }
355                 }
356             } else {
357                 val result = schemas.findFirst[n|n.QName.localName.equals(localName)]
358                 if (result !== null) {
359                     return result;
360
361                 }
362             }
363         }
364         return null
365     }
366
367 }