blob: 500d1ebd38a66abd73ab63b17702c99ce3669641 [file] [log] [blame]
Aaron Kruglikovbc26a522017-02-21 11:27:49 -08001/*
2 * Copyright 2017-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.netconf.client.impl;
18
Thomas Vachuska59d24eb2017-03-22 10:57:34 -070019import org.apache.felix.scr.annotations.Service;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080020import org.onosproject.cluster.NodeId;
21import org.onosproject.net.DeviceId;
22import org.onosproject.netconf.client.NetconfTranslator;
23import org.onosproject.netconf.NetconfController;
24import org.onosproject.netconf.NetconfDevice;
25import org.onosproject.netconf.NetconfSession;
26
27import org.onosproject.yang.model.ResourceData;
28import org.onosproject.yang.model.KeyLeaf;
29import org.onosproject.yang.model.ListKey;
30import org.onosproject.yang.model.LeafListKey;
31import org.onosproject.yang.model.SchemaId;
32import org.onosproject.yang.model.DataNode;
33import org.onosproject.yang.model.NodeKey;
34import org.onosproject.yang.model.ResourceId;
35import org.onosproject.yang.model.InnerNode;
36import org.onosproject.yang.model.LeafNode;
37import org.onosproject.yang.model.SchemaContext;
38
39import org.onosproject.yang.runtime.DefaultCompositeData;
40import org.onosproject.yang.runtime.DefaultRuntimeContext;
41import org.onosproject.yang.runtime.YangRuntimeService;
42import org.onosproject.yang.runtime.YangModelRegistry;
43import org.onosproject.yang.runtime.DefaultCompositeStream;
44import org.onosproject.yang.runtime.CompositeStream;
45import org.onosproject.yang.runtime.DefaultAnnotatedNodeInfo;
46import org.onosproject.yang.runtime.DefaultAnnotation;
47import org.onosproject.yang.runtime.DefaultResourceData;
48import org.onosproject.yang.runtime.YangSerializerContext;
49import org.onosproject.yang.runtime.DefaultYangSerializerContext;
50/*FIXME these imports are not visible using OSGI*/
51import org.onosproject.yang.runtime.helperutils.SerializerHelper;
52
53import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_LEAF_VALUE_NODE;
54import static org.onosproject.yang.runtime.helperutils.SerializerHelper.addDataNode;
55
56import java.io.BufferedReader;
57import java.io.ByteArrayInputStream;
58import java.io.IOException;
59import java.io.InputStream;
60import java.io.InputStreamReader;
61import java.nio.charset.StandardCharsets;
62import java.util.regex.Matcher;
63import java.util.regex.Pattern;
64import java.util.List;
65import java.util.Iterator;
66
67import com.google.common.annotations.Beta;
68
69import org.apache.felix.scr.annotations.Activate;
70import org.apache.felix.scr.annotations.Component;
71import org.apache.felix.scr.annotations.Deactivate;
72import org.apache.felix.scr.annotations.Reference;
73import org.apache.felix.scr.annotations.ReferenceCardinality;
74
75import org.osgi.service.component.ComponentContext;
76
77import org.slf4j.Logger;
78import org.slf4j.LoggerFactory;
79
80import static com.google.common.base.Preconditions.checkNotNull;
81
82/*TODO once the API's are finalized this comment will be made more specified.*/
83/**
84 * Translator which accepts data types defined for the DynamicConfigService and
85 * makes the appropriate calls to NETCONF devices before encoding and returning
86 * responses in formats suitable for the DynamicConfigService.
87 *
88 * NOTE: This entity does not ensure you are the master of a device you attempt
89 * to contact. If you are not the master an error will be thrown because there
90 * will be no session available.
91 */
92@Beta
Thomas Vachuska59d24eb2017-03-22 10:57:34 -070093@Service
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080094@Component(immediate = true)
95public class NetconfTranslatorImpl implements NetconfTranslator {
96
97 private final Logger log = LoggerFactory
98 .getLogger(getClass());
99
100 private NodeId localNodeId;
101
102 private static final String GET_CONFIG_MESSAGE_REGEX =
103 "<data>\n?\\s*(.*?)\n?\\s*</data>";
104 private static final int GET_CONFIG_CORE_MESSAGE_GROUP = 1;
105 private static final Pattern GET_CONFIG_CORE_MESSAGE_PATTERN =
106 Pattern.compile(GET_CONFIG_MESSAGE_REGEX, Pattern.DOTALL);
107 private static final String GET_CORE_MESSAGE_REGEX = "<data>\n?\\s*(.*?)\n?\\s*</data>";
108 private static final int GET_CORE_MESSAGE_GROUP = 1;
109 private static final Pattern GET_CORE_MESSAGE_PATTERN =
110 Pattern.compile(GET_CORE_MESSAGE_REGEX, Pattern.DOTALL);
111
112 private static final String NETCONF_1_0_BASE_NAMESPACE =
113 "urn:ietf:params:xml:ns:netconf:base:1.0";
114
115 private static final String GET_URI = "urn:ietf:params:xml:ns:yang:" +
116 "yrt-ietf-network:networks/network/node";
117 private static final String XML_ENCODING_SPECIFIER = "XML";
118 private static final String OP_SPECIFIER = "xc:operation";
119 private static final String REPLACE_OP_SPECIFIER = "replace";
120 private static final String DELETE_OP_SPECIFIER = "delete";
121 private static final String XMLNS_XC_SPECIFIER = "xmlns:xc";
122 private static final String XMLNS_SPECIFIER = "xmlns";
123
124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
125 protected NetconfController netconfController;
126
127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
128 protected YangRuntimeService yangRuntimeService;
129
130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected YangModelRegistry yangModelRegistry;
132
133 @Activate
134 public void activate(ComponentContext context) {
135 log.info("Started");
136 }
137
138 @Deactivate
139 public void deactivate() {
140 log.info("Stopped");
141 }
142
143 @Override
144 public ResourceData getDeviceConfig(DeviceId deviceId) throws IOException {
145 NetconfSession session = getNetconfSession(deviceId);
146 /*FIXME "running" will be replaced with an enum once netconf supports multiple datastores.*/
147 String reply = session.getConfig("running");
148 Matcher protocolStripper = GET_CONFIG_CORE_MESSAGE_PATTERN.matcher(reply);
149 reply = protocolStripper.group(GET_CONFIG_CORE_MESSAGE_GROUP);
150 return yangRuntimeService.decode(
151 new DefaultCompositeStream(
152 null,
153 /*FIXME is UTF_8 the appropriate encoding? */
154 new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8))),
155 new DefaultRuntimeContext.Builder()
156 .setDataFormat(XML_ENCODING_SPECIFIER)
157 .addAnnotation(
158 new DefaultAnnotation(XMLNS_SPECIFIER,
159 NETCONF_1_0_BASE_NAMESPACE))
160 .build()).resourceData();
161 }
162
163 @Override
164 public boolean editDeviceConfig(DeviceId deviceId, ResourceData resourceData,
165 NetconfTranslator.OperationType operationType) throws IOException {
166 NetconfSession session = getNetconfSession(deviceId);
167 ResourceData modifiedPathResourceData = getResourceData(resourceData.resourceId(),
168 resourceData.dataNodes(),
169 new DefaultYangSerializerContext(
170 (SchemaContext) yangModelRegistry, null));
171 DefaultCompositeData.Builder compositeDataBuilder = DefaultCompositeData
172 .builder()
173 .resourceData(modifiedPathResourceData);
174 for (DataNode node : resourceData.dataNodes()) {
175 ResourceId resourceId = resourceData.resourceId();
176 if (operationType != OperationType.DELETE) {
177 resourceId = getAnnotatedNodeResourceId(resourceData.resourceId(), node);
178 }
179 if (resourceId != null) {
180 DefaultAnnotatedNodeInfo.Builder annotatedNodeInfo = DefaultAnnotatedNodeInfo.builder();
181 annotatedNodeInfo.resourceId(resourceId);
182 annotatedNodeInfo.addAnnotation(new DefaultAnnotation(OP_SPECIFIER,
183 operationType == OperationType.DELETE ?
184 DELETE_OP_SPECIFIER : REPLACE_OP_SPECIFIER));
185 compositeDataBuilder.addAnnotatedNodeInfo(annotatedNodeInfo.build());
186 }
187 }
188 CompositeStream config = yangRuntimeService.encode(compositeDataBuilder.build(),
189 new DefaultRuntimeContext.Builder()
190 .setDataFormat(XML_ENCODING_SPECIFIER)
191 .addAnnotation(
192 new DefaultAnnotation(
193 XMLNS_XC_SPECIFIER,
194 NETCONF_1_0_BASE_NAMESPACE))
195 .build());
196 /* FIXME need to fix to string conversion. */
197 if (session.editConfig(streamToString(config.resourceData()))) {
198 /* NOTE: a failure to edit is reflected as a NetconfException.*/
199 return true;
200 }
201 log.warn("Editing of the netconf device: {} failed.", deviceId);
202 return false;
203 }
204
205 @Override
206 public ResourceData getDeviceState(DeviceId deviceId) throws IOException {
207 NetconfSession session = getNetconfSession(deviceId);
208 /*TODO the first parameter will come into use if get is required to support filters.*/
209 String reply = session.get(null, null);
210 Matcher protocolStripper = GET_CORE_MESSAGE_PATTERN.matcher(reply);
211 reply = protocolStripper.group(GET_CORE_MESSAGE_GROUP);
212 return yangRuntimeService.decode(new DefaultCompositeStream(
213 null,
214 /*FIXME is UTF_8 the appropriate encoding? */
215 new ByteArrayInputStream(reply.toString().getBytes(StandardCharsets.UTF_8))),
216 new DefaultRuntimeContext.Builder()
217 .setDataFormat(XML_ENCODING_SPECIFIER)
218 .addAnnotation(
219 new DefaultAnnotation(
220 XMLNS_SPECIFIER,
221 NETCONF_1_0_BASE_NAMESPACE))
222 .build()).resourceData();
223 /* NOTE: a failure to get is reflected as a NetconfException.*/
224 }
225
226 /**
227 * Returns a session for the specified deviceId if this node is its master,
228 * returns null otherwise.
229 * @param deviceId the id of node for witch we wish to retrieve a session
230 * @return a NetconfSession with the specified node or null
231 */
232 private NetconfSession getNetconfSession(DeviceId deviceId) {
233 NetconfDevice device = netconfController.getNetconfDevice(deviceId);
234 checkNotNull(device, "The specified deviceId could not be found by the NETCONF controller.");
235 NetconfSession session = device.getSession();
236 checkNotNull(session, "A session could not be retrieved for the specified deviceId.");
237 return session;
238 }
239
240 /**
241 * Accepts a stream and converts it to a string.
242 *
243 * @param stream the stream to be converted
244 * @return a string with the same sequence of characters as the stream
245 * @throws IOException if reading from the stream fails
246 */
247 private String streamToString(InputStream stream) throws IOException {
248 BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
249 StringBuilder builder = new StringBuilder();
250
251 String nextLine = reader.readLine();
252 while (nextLine != null) {
253 builder.append(nextLine);
254 nextLine = reader.readLine();
255 }
256 return builder.toString();
257 }
258
259 /**
260 * Returns resource data having resource id as "/" and data node tree
261 * starting from "/" by creating data nodes for given resource id(parent
262 * node for given list of nodes) and list of child nodes.
263 *
264 * This api will be used in encode flow only.
265 *
266 * @param rid resource identifier till parent node
267 * @param nodes list of data nodes
268 * @param cont yang serializer context
269 * @return resource data.
270 */
271 public static ResourceData getResourceData(
272 ResourceId rid, List<DataNode> nodes, YangSerializerContext cont) {
273 List<NodeKey> keys = rid.nodeKeys();
274 Iterator<NodeKey> it = keys.iterator();
275 DataNode.Builder dbr = SerializerHelper.initializeDataNode(cont);
276
277 // checking the resource id weather it is getting started from / or not
278 if (it.next().schemaId().name() != "/") {
279 //exception
280 }
281
282 while (it.hasNext()) {
283 NodeKey nodekey = it.next();
284 SchemaId sid = nodekey.schemaId();
285 dbr = addDataNode(dbr, sid.name(), sid.namespace(),
286 null, null);
287 if (nodekey instanceof ListKey) {
288 for (KeyLeaf keyLeaf : ((ListKey) nodekey).keyLeafs()) {
289 String val;
290 if (keyLeaf.leafValue() == null) {
291 val = null;
292 } else {
293 val = keyLeaf.leafValAsString();
294 }
295 dbr = addDataNode(dbr, keyLeaf.leafSchema().name(),
296 sid.namespace(), val,
297 SINGLE_INSTANCE_LEAF_VALUE_NODE);
298 }
299 }
300 }
301
302 if (dbr instanceof LeafNode.Builder &&
303 (nodes != null || !nodes.isEmpty())) {
304 //exception "leaf/leaf-list can not have child node"
305 }
306
307 if (nodes != null && !nodes.isEmpty()) {
308 // adding the parent node for given list of nodes
309 for (DataNode node : nodes) {
310 dbr = ((InnerNode.Builder) dbr).addNode(node);
311 }
312 }
313/*FIXME this can be uncommented for use with versions of onos-yang-tools newer than 1.12.0-b6 */
314// while (dbr.parent() != null) {
315// dbr = SerializerHelper.exitDataNode(dbr);
316// }
317
318 ResourceData.Builder resData = DefaultResourceData.builder();
319
320 resData.addDataNode(dbr.build());
321 resData.resourceId(null);
322 return resData.build();
323 }
324 /**
325 * Returns resource id for annotated data node by adding resource id of top
326 * level data node to given resource id.
327 *
328 * Annotation will be added to node based on the updated resource id.
329 * This api will be used in encode flow only.
330 *
331 * @param rid resource identifier till parent node
332 * @param node data node
333 * @return updated resource id.
334 */
335 public static ResourceId getAnnotatedNodeResourceId(ResourceId rid,
336 DataNode node) {
337
338 String val;
339 ResourceId.Builder rIdBldr = ResourceId.builder();
340 try {
341 rIdBldr = rid.copyBuilder();
342 } catch (CloneNotSupportedException e) {
343 e.printStackTrace();
344 }
345 DataNode.Type type = node.type();
346 NodeKey k = node.key();
347 SchemaId sid = k.schemaId();
348
349 switch (type) {
350
351 case MULTI_INSTANCE_LEAF_VALUE_NODE:
352 val = ((LeafListKey) k).value().toString();
353 rIdBldr.addLeafListBranchPoint(sid.name(), sid.namespace(), val);
354 break;
355
356 case MULTI_INSTANCE_NODE:
357 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
358// Preparing the list of key values for multiInstanceNode
359 for (KeyLeaf keyLeaf : ((ListKey) node.key()).keyLeafs()) {
360 val = keyLeaf.leafValAsString();
361 rIdBldr.addKeyLeaf(keyLeaf.leafSchema().name(), sid.namespace(), val);
362 }
363 break;
364 case SINGLE_INSTANCE_LEAF_VALUE_NODE:
365 case SINGLE_INSTANCE_NODE:
366 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
367 break;
368
369 default:
370 throw new IllegalArgumentException();
371 }
372 return rIdBldr.build();
373 }
374}