blob: 6e38729a07aabc223da0a8c5a126da55a6436ee4 [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;
Aaron Kruglikovd24dc982017-03-23 18:48:58 -070031import org.onosproject.yang.model.SchemaContext;
32import org.onosproject.yang.model.SchemaContextProvider;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080033import org.onosproject.yang.model.SchemaId;
34import org.onosproject.yang.model.DataNode;
35import org.onosproject.yang.model.NodeKey;
36import org.onosproject.yang.model.ResourceId;
37import org.onosproject.yang.model.InnerNode;
38import org.onosproject.yang.model.LeafNode;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080039
40import org.onosproject.yang.runtime.DefaultCompositeData;
41import org.onosproject.yang.runtime.DefaultRuntimeContext;
42import org.onosproject.yang.runtime.YangRuntimeService;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080043import 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)
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700131 protected SchemaContextProvider schemaContextProvider;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800132
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);
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700167 SchemaContext context = schemaContextProvider
168 .getSchemaContext(ResourceId.builder().addBranchPointSchema("/", null).build());
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800169 ResourceData modifiedPathResourceData = getResourceData(resourceData.resourceId(),
170 resourceData.dataNodes(),
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700171 new DefaultYangSerializerContext(context, null));
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800172 DefaultCompositeData.Builder compositeDataBuilder = DefaultCompositeData
173 .builder()
174 .resourceData(modifiedPathResourceData);
175 for (DataNode node : resourceData.dataNodes()) {
176 ResourceId resourceId = resourceData.resourceId();
177 if (operationType != OperationType.DELETE) {
178 resourceId = getAnnotatedNodeResourceId(resourceData.resourceId(), node);
179 }
180 if (resourceId != null) {
181 DefaultAnnotatedNodeInfo.Builder annotatedNodeInfo = DefaultAnnotatedNodeInfo.builder();
182 annotatedNodeInfo.resourceId(resourceId);
183 annotatedNodeInfo.addAnnotation(new DefaultAnnotation(OP_SPECIFIER,
184 operationType == OperationType.DELETE ?
185 DELETE_OP_SPECIFIER : REPLACE_OP_SPECIFIER));
186 compositeDataBuilder.addAnnotatedNodeInfo(annotatedNodeInfo.build());
187 }
188 }
189 CompositeStream config = yangRuntimeService.encode(compositeDataBuilder.build(),
190 new DefaultRuntimeContext.Builder()
191 .setDataFormat(XML_ENCODING_SPECIFIER)
192 .addAnnotation(
193 new DefaultAnnotation(
194 XMLNS_XC_SPECIFIER,
195 NETCONF_1_0_BASE_NAMESPACE))
196 .build());
197 /* FIXME need to fix to string conversion. */
198 if (session.editConfig(streamToString(config.resourceData()))) {
199 /* NOTE: a failure to edit is reflected as a NetconfException.*/
200 return true;
201 }
202 log.warn("Editing of the netconf device: {} failed.", deviceId);
203 return false;
204 }
205
206 @Override
207 public ResourceData getDeviceState(DeviceId deviceId) throws IOException {
208 NetconfSession session = getNetconfSession(deviceId);
209 /*TODO the first parameter will come into use if get is required to support filters.*/
210 String reply = session.get(null, null);
211 Matcher protocolStripper = GET_CORE_MESSAGE_PATTERN.matcher(reply);
212 reply = protocolStripper.group(GET_CORE_MESSAGE_GROUP);
213 return yangRuntimeService.decode(new DefaultCompositeStream(
214 null,
215 /*FIXME is UTF_8 the appropriate encoding? */
216 new ByteArrayInputStream(reply.toString().getBytes(StandardCharsets.UTF_8))),
217 new DefaultRuntimeContext.Builder()
218 .setDataFormat(XML_ENCODING_SPECIFIER)
219 .addAnnotation(
220 new DefaultAnnotation(
221 XMLNS_SPECIFIER,
222 NETCONF_1_0_BASE_NAMESPACE))
223 .build()).resourceData();
224 /* NOTE: a failure to get is reflected as a NetconfException.*/
225 }
226
227 /**
228 * Returns a session for the specified deviceId if this node is its master,
229 * returns null otherwise.
230 * @param deviceId the id of node for witch we wish to retrieve a session
231 * @return a NetconfSession with the specified node or null
232 */
233 private NetconfSession getNetconfSession(DeviceId deviceId) {
234 NetconfDevice device = netconfController.getNetconfDevice(deviceId);
235 checkNotNull(device, "The specified deviceId could not be found by the NETCONF controller.");
236 NetconfSession session = device.getSession();
237 checkNotNull(session, "A session could not be retrieved for the specified deviceId.");
238 return session;
239 }
240
241 /**
242 * Accepts a stream and converts it to a string.
243 *
244 * @param stream the stream to be converted
245 * @return a string with the same sequence of characters as the stream
246 * @throws IOException if reading from the stream fails
247 */
248 private String streamToString(InputStream stream) throws IOException {
249 BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
250 StringBuilder builder = new StringBuilder();
251
252 String nextLine = reader.readLine();
253 while (nextLine != null) {
254 builder.append(nextLine);
255 nextLine = reader.readLine();
256 }
257 return builder.toString();
258 }
259
260 /**
261 * Returns resource data having resource id as "/" and data node tree
262 * starting from "/" by creating data nodes for given resource id(parent
263 * node for given list of nodes) and list of child nodes.
264 *
265 * This api will be used in encode flow only.
266 *
267 * @param rid resource identifier till parent node
268 * @param nodes list of data nodes
269 * @param cont yang serializer context
270 * @return resource data.
271 */
272 public static ResourceData getResourceData(
273 ResourceId rid, List<DataNode> nodes, YangSerializerContext cont) {
274 List<NodeKey> keys = rid.nodeKeys();
275 Iterator<NodeKey> it = keys.iterator();
276 DataNode.Builder dbr = SerializerHelper.initializeDataNode(cont);
277
278 // checking the resource id weather it is getting started from / or not
279 if (it.next().schemaId().name() != "/") {
280 //exception
281 }
282
283 while (it.hasNext()) {
284 NodeKey nodekey = it.next();
285 SchemaId sid = nodekey.schemaId();
286 dbr = addDataNode(dbr, sid.name(), sid.namespace(),
287 null, null);
288 if (nodekey instanceof ListKey) {
289 for (KeyLeaf keyLeaf : ((ListKey) nodekey).keyLeafs()) {
290 String val;
291 if (keyLeaf.leafValue() == null) {
292 val = null;
293 } else {
294 val = keyLeaf.leafValAsString();
295 }
296 dbr = addDataNode(dbr, keyLeaf.leafSchema().name(),
297 sid.namespace(), val,
298 SINGLE_INSTANCE_LEAF_VALUE_NODE);
299 }
300 }
301 }
302
303 if (dbr instanceof LeafNode.Builder &&
304 (nodes != null || !nodes.isEmpty())) {
305 //exception "leaf/leaf-list can not have child node"
306 }
307
308 if (nodes != null && !nodes.isEmpty()) {
309 // adding the parent node for given list of nodes
310 for (DataNode node : nodes) {
311 dbr = ((InnerNode.Builder) dbr).addNode(node);
312 }
313 }
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700314/*FIXME this can be uncommented for use with versions of onos-yang-tools newer than 1.12.0-b6*/
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800315// while (dbr.parent() != null) {
316// dbr = SerializerHelper.exitDataNode(dbr);
317// }
318
319 ResourceData.Builder resData = DefaultResourceData.builder();
320
321 resData.addDataNode(dbr.build());
322 resData.resourceId(null);
323 return resData.build();
324 }
325 /**
326 * Returns resource id for annotated data node by adding resource id of top
327 * level data node to given resource id.
328 *
329 * Annotation will be added to node based on the updated resource id.
330 * This api will be used in encode flow only.
331 *
332 * @param rid resource identifier till parent node
333 * @param node data node
334 * @return updated resource id.
335 */
336 public static ResourceId getAnnotatedNodeResourceId(ResourceId rid,
337 DataNode node) {
338
339 String val;
340 ResourceId.Builder rIdBldr = ResourceId.builder();
341 try {
342 rIdBldr = rid.copyBuilder();
343 } catch (CloneNotSupportedException e) {
344 e.printStackTrace();
345 }
346 DataNode.Type type = node.type();
347 NodeKey k = node.key();
348 SchemaId sid = k.schemaId();
349
350 switch (type) {
351
352 case MULTI_INSTANCE_LEAF_VALUE_NODE:
353 val = ((LeafListKey) k).value().toString();
354 rIdBldr.addLeafListBranchPoint(sid.name(), sid.namespace(), val);
355 break;
356
357 case MULTI_INSTANCE_NODE:
358 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
359// Preparing the list of key values for multiInstanceNode
360 for (KeyLeaf keyLeaf : ((ListKey) node.key()).keyLeafs()) {
361 val = keyLeaf.leafValAsString();
362 rIdBldr.addKeyLeaf(keyLeaf.leafSchema().name(), sid.namespace(), val);
363 }
364 break;
365 case SINGLE_INSTANCE_LEAF_VALUE_NODE:
366 case SINGLE_INSTANCE_NODE:
367 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
368 break;
369
370 default:
371 throw new IllegalArgumentException();
372 }
373 return rIdBldr.build();
374 }
375}