blob: b66a63e9747fbfdee2c628578a11c535880af34e [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
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053019import com.google.common.annotations.Beta;
20import org.apache.felix.scr.annotations.Activate;
21import org.apache.felix.scr.annotations.Component;
22import org.apache.felix.scr.annotations.Deactivate;
23import org.apache.felix.scr.annotations.Reference;
24import org.apache.felix.scr.annotations.ReferenceCardinality;
Thomas Vachuska59d24eb2017-03-22 10:57:34 -070025import org.apache.felix.scr.annotations.Service;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080026import org.onosproject.cluster.NodeId;
27import org.onosproject.net.DeviceId;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080028import org.onosproject.netconf.NetconfController;
29import org.onosproject.netconf.NetconfDevice;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053030import org.onosproject.netconf.NetconfException;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080031import org.onosproject.netconf.NetconfSession;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053032import org.onosproject.netconf.client.NetconfTranslator;
33import org.onosproject.yang.model.DataNode;
34import org.onosproject.yang.model.InnerNode;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080035import org.onosproject.yang.model.KeyLeaf;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080036import org.onosproject.yang.model.LeafListKey;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053037import org.onosproject.yang.model.LeafNode;
38import org.onosproject.yang.model.ListKey;
39import org.onosproject.yang.model.NodeKey;
40import org.onosproject.yang.model.ResourceData;
41import org.onosproject.yang.model.ResourceId;
Aaron Kruglikovd24dc982017-03-23 18:48:58 -070042import org.onosproject.yang.model.SchemaContext;
43import org.onosproject.yang.model.SchemaContextProvider;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080044import org.onosproject.yang.model.SchemaId;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080045import org.onosproject.yang.runtime.CompositeStream;
46import org.onosproject.yang.runtime.DefaultAnnotatedNodeInfo;
47import org.onosproject.yang.runtime.DefaultAnnotation;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053048import org.onosproject.yang.runtime.DefaultCompositeData;
49import org.onosproject.yang.runtime.DefaultCompositeStream;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080050import org.onosproject.yang.runtime.DefaultResourceData;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053051import org.onosproject.yang.runtime.DefaultRuntimeContext;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080052import org.onosproject.yang.runtime.DefaultYangSerializerContext;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053053import org.onosproject.yang.runtime.YangRuntimeService;
54import org.onosproject.yang.runtime.YangSerializerContext;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080055import org.onosproject.yang.runtime.helperutils.SerializerHelper;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053056import org.osgi.service.component.ComponentContext;
57import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080059
60import java.io.BufferedReader;
61import java.io.ByteArrayInputStream;
62import java.io.IOException;
63import java.io.InputStream;
64import java.io.InputStreamReader;
65import java.nio.charset.StandardCharsets;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053066import java.util.Iterator;
67import java.util.List;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080068import java.util.regex.Matcher;
69import java.util.regex.Pattern;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080070
71import static com.google.common.base.Preconditions.checkNotNull;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053072import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_LEAF_VALUE_NODE;
73import static org.onosproject.yang.runtime.helperutils.SerializerHelper.addDataNode;
74
75/*FIXME these imports are not visible using OSGI*/
76
77/*FIXME these imports are not visible using OSGI*/
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080078
79/*TODO once the API's are finalized this comment will be made more specified.*/
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053080
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080081/**
82 * Translator which accepts data types defined for the DynamicConfigService and
83 * makes the appropriate calls to NETCONF devices before encoding and returning
84 * responses in formats suitable for the DynamicConfigService.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053085 * <p>
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080086 * NOTE: This entity does not ensure you are the master of a device you attempt
87 * to contact. If you are not the master an error will be thrown because there
88 * will be no session available.
89 */
90@Beta
Thomas Vachuska59d24eb2017-03-22 10:57:34 -070091@Service
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080092@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";
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530115 private static final String XML_ENCODING_SPECIFIER = "xml";
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800116 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)
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700129 protected SchemaContextProvider schemaContextProvider;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800130
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);
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700165 SchemaContext context = schemaContextProvider
166 .getSchemaContext(ResourceId.builder().addBranchPointSchema("/", null).build());
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800167 ResourceData modifiedPathResourceData = getResourceData(resourceData.resourceId(),
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530168 resourceData.dataNodes(),
169 new DefaultYangSerializerContext(context, null));
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800170 DefaultCompositeData.Builder compositeDataBuilder = DefaultCompositeData
171 .builder()
172 .resourceData(modifiedPathResourceData);
173 for (DataNode node : resourceData.dataNodes()) {
174 ResourceId resourceId = resourceData.resourceId();
175 if (operationType != OperationType.DELETE) {
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530176 resourceId = getAnnotatedNodeResourceId(
177 resourceData.resourceId(), node);
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800178 }
179 if (resourceId != null) {
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530180 DefaultAnnotatedNodeInfo.Builder annotatedNodeInfo =
181 DefaultAnnotatedNodeInfo.builder();
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800182 annotatedNodeInfo.resourceId(resourceId);
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530183 annotatedNodeInfo.addAnnotation(
184 new DefaultAnnotation(
185 OP_SPECIFIER, operationType == OperationType.DELETE ?
186 DELETE_OP_SPECIFIER : REPLACE_OP_SPECIFIER));
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800187 compositeDataBuilder.addAnnotatedNodeInfo(annotatedNodeInfo.build());
188 }
189 }
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530190 CompositeStream config = yangRuntimeService.encode(
191 compositeDataBuilder.build(),
192 new DefaultRuntimeContext.Builder()
193 .setDataFormat(XML_ENCODING_SPECIFIER)
194 .addAnnotation(new DefaultAnnotation(
195 XMLNS_XC_SPECIFIER, NETCONF_1_0_BASE_NAMESPACE))
196 .build());
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800197 /* FIXME need to fix to string conversion. */
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530198
199 try {
200 String reply = session.requestSync(Utils.editConfig(streamToString(
201 config.resourceData())));
202 } catch (NetconfException e) {
203 log.error("failed to send a request sync", e);
204 return false;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800205 }
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530206 /* NOTE: a failure to edit is reflected as a NetconfException.*/
207 return true;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800208 }
209
210 @Override
211 public ResourceData getDeviceState(DeviceId deviceId) throws IOException {
212 NetconfSession session = getNetconfSession(deviceId);
213 /*TODO the first parameter will come into use if get is required to support filters.*/
214 String reply = session.get(null, null);
215 Matcher protocolStripper = GET_CORE_MESSAGE_PATTERN.matcher(reply);
216 reply = protocolStripper.group(GET_CORE_MESSAGE_GROUP);
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530217 return yangRuntimeService.decode(
218 new DefaultCompositeStream(
219 null,
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800220 /*FIXME is UTF_8 the appropriate encoding? */
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530221 new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8))),
222 new DefaultRuntimeContext.Builder()
223 .setDataFormat(XML_ENCODING_SPECIFIER)
224 .addAnnotation(
225 new DefaultAnnotation(
226 XMLNS_SPECIFIER,
227 NETCONF_1_0_BASE_NAMESPACE))
228 .build()).resourceData();
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800229 /* NOTE: a failure to get is reflected as a NetconfException.*/
230 }
231
232 /**
233 * Returns a session for the specified deviceId if this node is its master,
234 * returns null otherwise.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530235 *
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800236 * @param deviceId the id of node for witch we wish to retrieve a session
237 * @return a NetconfSession with the specified node or null
238 */
239 private NetconfSession getNetconfSession(DeviceId deviceId) {
240 NetconfDevice device = netconfController.getNetconfDevice(deviceId);
241 checkNotNull(device, "The specified deviceId could not be found by the NETCONF controller.");
242 NetconfSession session = device.getSession();
243 checkNotNull(session, "A session could not be retrieved for the specified deviceId.");
244 return session;
245 }
246
247 /**
248 * Accepts a stream and converts it to a string.
249 *
250 * @param stream the stream to be converted
251 * @return a string with the same sequence of characters as the stream
252 * @throws IOException if reading from the stream fails
253 */
254 private String streamToString(InputStream stream) throws IOException {
255 BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
256 StringBuilder builder = new StringBuilder();
257
258 String nextLine = reader.readLine();
259 while (nextLine != null) {
260 builder.append(nextLine);
261 nextLine = reader.readLine();
262 }
263 return builder.toString();
264 }
265
266 /**
267 * Returns resource data having resource id as "/" and data node tree
268 * starting from "/" by creating data nodes for given resource id(parent
269 * node for given list of nodes) and list of child nodes.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530270 * <p>
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800271 * This api will be used in encode flow only.
272 *
273 * @param rid resource identifier till parent node
274 * @param nodes list of data nodes
275 * @param cont yang serializer context
276 * @return resource data.
277 */
278 public static ResourceData getResourceData(
279 ResourceId rid, List<DataNode> nodes, YangSerializerContext cont) {
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530280 if (rid == null) {
281 ResourceData.Builder resData = DefaultResourceData.builder();
282 for (DataNode node : nodes) {
283 resData.addDataNode(node);
284 }
285 return resData.build();
286 }
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800287 List<NodeKey> keys = rid.nodeKeys();
288 Iterator<NodeKey> it = keys.iterator();
289 DataNode.Builder dbr = SerializerHelper.initializeDataNode(cont);
290
291 // checking the resource id weather it is getting started from / or not
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800292
293 while (it.hasNext()) {
294 NodeKey nodekey = it.next();
295 SchemaId sid = nodekey.schemaId();
296 dbr = addDataNode(dbr, sid.name(), sid.namespace(),
297 null, null);
298 if (nodekey instanceof ListKey) {
299 for (KeyLeaf keyLeaf : ((ListKey) nodekey).keyLeafs()) {
300 String val;
301 if (keyLeaf.leafValue() == null) {
302 val = null;
303 } else {
304 val = keyLeaf.leafValAsString();
305 }
306 dbr = addDataNode(dbr, keyLeaf.leafSchema().name(),
307 sid.namespace(), val,
308 SINGLE_INSTANCE_LEAF_VALUE_NODE);
309 }
310 }
311 }
312
313 if (dbr instanceof LeafNode.Builder &&
314 (nodes != null || !nodes.isEmpty())) {
315 //exception "leaf/leaf-list can not have child node"
316 }
317
318 if (nodes != null && !nodes.isEmpty()) {
319 // adding the parent node for given list of nodes
320 for (DataNode node : nodes) {
321 dbr = ((InnerNode.Builder) dbr).addNode(node);
322 }
323 }
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700324/*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 -0800325// while (dbr.parent() != null) {
326// dbr = SerializerHelper.exitDataNode(dbr);
327// }
328
329 ResourceData.Builder resData = DefaultResourceData.builder();
330
331 resData.addDataNode(dbr.build());
332 resData.resourceId(null);
333 return resData.build();
334 }
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530335
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800336 /**
337 * Returns resource id for annotated data node by adding resource id of top
338 * level data node to given resource id.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530339 * <p>
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800340 * Annotation will be added to node based on the updated resource id.
341 * This api will be used in encode flow only.
342 *
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530343 * @param rid resource identifier till parent node
344 * @param node data node
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800345 * @return updated resource id.
346 */
347 public static ResourceId getAnnotatedNodeResourceId(ResourceId rid,
348 DataNode node) {
349
350 String val;
351 ResourceId.Builder rIdBldr = ResourceId.builder();
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530352 if (rid != null) {
353 try {
354 rIdBldr = rid.copyBuilder();
355 } catch (CloneNotSupportedException e) {
356 e.printStackTrace();
357 }
358 } else {
359 rIdBldr.addBranchPointSchema("/", null);
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800360 }
361 DataNode.Type type = node.type();
362 NodeKey k = node.key();
363 SchemaId sid = k.schemaId();
364
365 switch (type) {
366
367 case MULTI_INSTANCE_LEAF_VALUE_NODE:
368 val = ((LeafListKey) k).value().toString();
369 rIdBldr.addLeafListBranchPoint(sid.name(), sid.namespace(), val);
370 break;
371
372 case MULTI_INSTANCE_NODE:
373 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
374// Preparing the list of key values for multiInstanceNode
375 for (KeyLeaf keyLeaf : ((ListKey) node.key()).keyLeafs()) {
376 val = keyLeaf.leafValAsString();
377 rIdBldr.addKeyLeaf(keyLeaf.leafSchema().name(), sid.namespace(), val);
378 }
379 break;
380 case SINGLE_INSTANCE_LEAF_VALUE_NODE:
381 case SINGLE_INSTANCE_NODE:
382 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
383 break;
384
385 default:
386 throw new IllegalArgumentException();
387 }
388 return rIdBldr.build();
389 }
390}