Fix race conditions between config-manager and persister.
[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.HashBiMap
5 import java.net.URI
6 import java.net.URLDecoder
7 import java.net.URLEncoder
8 import java.util.HashMap
9 import java.util.List
10 import java.util.Map
11 import java.util.concurrent.ConcurrentHashMap
12 import javax.ws.rs.core.Response
13 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener
14 import org.opendaylight.controller.sal.rest.impl.RestconfProvider
15 import org.opendaylight.yangtools.yang.common.QName
16 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
17 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
18 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument
21 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
22 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
23 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
24 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
25 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
26 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
27 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
28 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext
30
31 import static com.google.common.base.Preconditions.*
32
33 class ControllerContext implements SchemaServiceListener {
34
35     val static ControllerContext INSTANCE = new ControllerContext
36
37     val static NULL_VALUE = "null"
38
39     @Property
40     SchemaContext schemas;
41
42     private val BiMap<URI, String> uriToModuleName = HashBiMap.create();
43     private val Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
44     private val Map<QName,RpcDefinition> qnameToRpc = new ConcurrentHashMap();
45     
46
47     private new() {
48         if (INSTANCE !== null) {
49             throw new IllegalStateException("Already instantiated");
50         }
51     }
52
53     static def getInstance() {
54         return INSTANCE
55     }
56     
57     private def void checkPreconditions() {
58         if (schemas === null) {
59             throw new ResponseException(Response.Status.SERVICE_UNAVAILABLE, RestconfProvider::NOT_INITALIZED_MSG)
60         }
61     }
62
63     public def InstanceIdWithSchemaNode toInstanceIdentifier(String restconfInstance) {
64         val ret = InstanceIdentifier.builder();
65         val pathArgs = restconfInstance.split("/");
66         if (pathArgs.empty) {
67             return null;
68         }
69         if (pathArgs.head.empty) {
70             pathArgs.remove(0)
71         }
72         val schemaNode = ret.collectPathArguments(pathArgs, restconfInstance.findModule);
73         if (schemaNode === null) {
74             return null
75         }
76         new InstanceIdWithSchemaNode(ret.toInstance, schemaNode)
77     }
78
79     private def findModule(String restconfInstance) {
80         checkPreconditions
81         checkNotNull(restconfInstance);
82         val pathArgs = restconfInstance.split("/");
83         if (pathArgs.empty) {
84             return null;
85         }
86         val modulWithFirstYangStatement = pathArgs.filter[s|s.contains(":")].head
87         val startModule = modulWithFirstYangStatement.toModuleName();
88         schemas.getLatestModule(startModule)
89     }
90
91     private def getLatestModule(SchemaContext schema, String moduleName) {
92         checkNotNull(schema)
93         checkArgument(moduleName !== null && !moduleName.empty)
94         val modules = schema.modules.filter[m|m.name == moduleName]
95         var latestModule = modules.head
96         for (module : modules) {
97             if (module.revision.after(latestModule.revision)) {
98                 latestModule = module
99             }
100         }
101         return latestModule
102     }
103
104     def String toFullRestconfIdentifier(InstanceIdentifier path) {
105         checkPreconditions
106         val elements = path.path;
107         val ret = new StringBuilder();
108         val startQName = elements.get(0).nodeType;
109         val initialModule = schemas.findModuleByNamespaceAndRevision(startQName.namespace, startQName.revision)
110         var node = initialModule as DataSchemaNode;
111         for (element : elements) {
112             node = node.childByQName(element.nodeType);
113             ret.append(element.toRestconfIdentifier(node));
114         }
115         return ret.toString
116     }
117
118     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifier argument, DataSchemaNode node) {
119         '''/«argument.nodeType.toRestconfIdentifier()»'''
120     }
121
122     private def dispatch CharSequence toRestconfIdentifier(NodeIdentifierWithPredicates argument, ListSchemaNode node) {
123         val nodeIdentifier = argument.nodeType.toRestconfIdentifier();
124         val keyValues = argument.keyValues;
125         return '''/«nodeIdentifier»/«FOR key : node.keyDefinition SEPARATOR "/"»«keyValues.get(key).toUriString»«ENDFOR»'''
126     }
127
128     private def dispatch CharSequence toRestconfIdentifier(PathArgument argument, DataSchemaNode node) {
129         throw new IllegalArgumentException("Conversion of generic path argument is not supported");
130     }
131
132     def CharSequence toRestconfIdentifier(QName qname) {
133         checkPreconditions
134         var module = uriToModuleName.get(qname.namespace)
135         if (module === null) {
136             val moduleSchema = schemas.findModuleByNamespaceAndRevision(qname.namespace, qname.revision);
137             if(moduleSchema === null) throw new IllegalArgumentException()
138             uriToModuleName.put(qname.namespace, moduleSchema.name)
139             module = moduleSchema.name;
140         }
141         return '''«module»:«qname.localName»''';
142     }
143
144     private static dispatch def DataSchemaNode childByQName(ChoiceNode container, QName name) {
145         for (caze : container.cases) {
146             val ret = caze.childByQName(name)
147             if (ret !== null) {
148                 return ret;
149             }
150         }
151         return null;
152     }
153
154     private static dispatch def DataSchemaNode childByQName(ChoiceCaseNode container, QName name) {
155         val ret = container.getDataChildByName(name);
156         return ret;
157     }
158
159     private static dispatch def DataSchemaNode childByQName(ContainerSchemaNode container, QName name) {
160         return container.dataNodeChildByQName(name);
161     }
162
163     private static dispatch def DataSchemaNode childByQName(ListSchemaNode container, QName name) {
164         return container.dataNodeChildByQName(name);
165     }
166
167     private static dispatch def DataSchemaNode childByQName(DataSchemaNode container, QName name) {
168         return null;
169     }
170
171     private static def DataSchemaNode dataNodeChildByQName(DataNodeContainer container, QName name) {
172         var ret = container.getDataChildByName(name);
173         if (ret === null) {
174
175             // Find in Choice Cases
176             for (node : container.childNodes) {
177                 if (node instanceof ChoiceCaseNode) {
178                     val caseNode = (node as ChoiceCaseNode);
179                     ret = caseNode.childByQName(name);
180                     if (ret !== null) {
181                         return ret;
182                     }
183                 }
184             }
185         }
186         return ret;
187     }
188
189     private def toUriString(Object object) {
190         if(object === null) return "";
191         return URLEncoder.encode(object.toString)
192     }
193
194     private def DataSchemaNode collectPathArguments(InstanceIdentifierBuilder builder, List<String> strings,
195         DataNodeContainer parentNode) {
196         checkNotNull(strings)
197         if (parentNode === null) {
198             return null;
199         }
200         if (strings.empty) {
201             return parentNode as DataSchemaNode;
202         }
203         val nodeRef = strings.head;
204
205         val nodeName = nodeRef.toNodeName();
206         val targetNode = parentNode.getDataChildByName(nodeName);
207         if (targetNode === null) {
208             val children = parentNode.childNodes
209             for (child : children) {
210                 if (child instanceof ChoiceNode) {
211                     val choice = child as ChoiceNode
212                     for (caze : choice.cases) {
213                         val result = builder.collectPathArguments(strings, caze as DataNodeContainer);
214                         if (result !== null)
215                             return result
216                     }
217                 }
218             }
219             return null
220         }
221         if (targetNode instanceof ChoiceNode) {
222             return null
223         }
224
225         // Number of consumed elements
226         var consumed = 1;
227         if (targetNode instanceof ListSchemaNode) {
228             val listNode = targetNode as ListSchemaNode;
229             val keysSize = listNode.keyDefinition.size
230
231             // every key has to be filled
232             if ((strings.length - consumed) < keysSize) {
233                 return null;
234             }
235             val uriKeyValues = strings.subList(consumed, consumed + keysSize);
236             val keyValues = new HashMap<QName, Object>();
237             var i = 0;
238             for (key : listNode.keyDefinition) {
239                 val uriKeyValue = uriKeyValues.get(i);
240
241                 // key value cannot be NULL
242                 if (uriKeyValue.equals(NULL_VALUE)) {
243                     return null
244                 }
245                 keyValues.addKeyValue(listNode.getDataChildByName(key), uriKeyValue);
246                 i = i + 1;
247             }
248             consumed = consumed + i;
249             builder.nodeWithKey(targetNode.QName, keyValues);
250         } else {
251
252             // Only one instance of node is allowed
253             builder.node(targetNode.QName);
254         }
255         if (targetNode instanceof DataNodeContainer) {
256             val remaining = strings.subList(consumed, strings.length);
257             val result = builder.collectPathArguments(remaining, targetNode as DataNodeContainer);
258             return result
259         }
260
261         return targetNode
262     }
263
264     private def void addKeyValue(HashMap<QName, Object> map, DataSchemaNode node, String uriValue) {
265         checkNotNull(uriValue);
266         checkArgument(node instanceof LeafSchemaNode);
267         val decoded = URLDecoder.decode(uriValue);
268         map.put(node.QName, decoded);
269
270     }
271
272     private def String toModuleName(String str) {
273         checkNotNull(str)
274         if (str.contains(":")) {
275             val args = str.split(":");
276             checkArgument(args.size === 2);
277             return args.get(0);
278         } else {
279             return null;
280         }
281     }
282
283     private def String toNodeName(String str) {
284         if (str.contains(":")) {
285             val args = str.split(":");
286             checkArgument(args.size === 2);
287             return args.get(1);
288         } else {
289             return str;
290         }
291     }
292
293     public def QName toQName(String name) {
294         val module = name.toModuleName;
295         val node = name.toNodeName;
296         val namespace = moduleNameToUri.get(module);
297         return new QName(namespace,null,node);
298     }
299
300     override onGlobalContextUpdated(SchemaContext context) {
301         this.schemas = context;
302         for(operation : context.operations) {
303             val qname = new QName(operation.QName.namespace,null,operation.QName.localName);
304             qnameToRpc.put(qname,operation);
305         }
306     }
307     
308     def ContainerSchemaNode getRpcOutputSchema(QName name) {
309         qnameToRpc.get(name)?.output;
310     }
311     
312     def ContainerSchemaNode getRpcInputSchema(QName name) {
313         qnameToRpc.get(name)?.input;
314     }
315
316 }