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