blob: 84ae19b10fb30339954ef02a74c526faa49354d2 [file] [log] [blame]
Aaron Kruglikovbc26a522017-02-21 11:27:49 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Aaron Kruglikovbc26a522017-02-21 11:27:49 -08003 *
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;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080020import org.onosproject.cluster.NodeId;
21import org.onosproject.net.DeviceId;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080022import org.onosproject.netconf.NetconfController;
23import org.onosproject.netconf.NetconfDevice;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053024import org.onosproject.netconf.NetconfException;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080025import org.onosproject.netconf.NetconfSession;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053026import org.onosproject.netconf.client.NetconfTranslator;
27import org.onosproject.yang.model.DataNode;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070028import org.onosproject.yang.model.DefaultResourceData;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053029import org.onosproject.yang.model.InnerNode;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080030import org.onosproject.yang.model.KeyLeaf;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080031import org.onosproject.yang.model.LeafListKey;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053032import org.onosproject.yang.model.LeafNode;
33import org.onosproject.yang.model.ListKey;
34import org.onosproject.yang.model.NodeKey;
35import org.onosproject.yang.model.ResourceData;
36import org.onosproject.yang.model.ResourceId;
Aaron Kruglikovd24dc982017-03-23 18:48:58 -070037import org.onosproject.yang.model.SchemaContext;
38import org.onosproject.yang.model.SchemaContextProvider;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080039import org.onosproject.yang.model.SchemaId;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080040import org.onosproject.yang.runtime.CompositeStream;
41import org.onosproject.yang.runtime.DefaultAnnotatedNodeInfo;
42import org.onosproject.yang.runtime.DefaultAnnotation;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053043import org.onosproject.yang.runtime.DefaultCompositeData;
44import org.onosproject.yang.runtime.DefaultCompositeStream;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053045import org.onosproject.yang.runtime.DefaultRuntimeContext;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080046import org.onosproject.yang.runtime.DefaultYangSerializerContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070047import org.onosproject.yang.runtime.SerializerHelper;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053048import org.onosproject.yang.runtime.YangRuntimeService;
49import org.onosproject.yang.runtime.YangSerializerContext;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053050import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070051import org.osgi.service.component.annotations.Activate;
52import org.osgi.service.component.annotations.Component;
53import org.osgi.service.component.annotations.Deactivate;
54import org.osgi.service.component.annotations.Reference;
55import org.osgi.service.component.annotations.ReferenceCardinality;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053056import org.slf4j.Logger;
57import org.slf4j.LoggerFactory;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080058
59import java.io.BufferedReader;
60import java.io.ByteArrayInputStream;
61import java.io.IOException;
62import java.io.InputStream;
63import java.io.InputStreamReader;
64import java.nio.charset.StandardCharsets;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053065import java.util.Iterator;
66import java.util.List;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080067import java.util.regex.Matcher;
68import java.util.regex.Pattern;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080069
70import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIdd7c3f82017-09-03 14:18:01 -070071import static org.onosproject.netconf.DatastoreId.RUNNING;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053072import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_LEAF_VALUE_NODE;
Ray Milkey86d1b0a2017-05-16 15:15:08 -070073import static org.onosproject.yang.runtime.SerializerHelper.addDataNode;
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +053074
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
Ray Milkeyd84f89b2018-08-17 14:54:17 -070091@Component(immediate = true, service = NetconfTranslator.class)
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080092public class NetconfTranslatorImpl implements NetconfTranslator {
93
Ray Milkeyba547f92018-02-01 15:22:31 -080094 private static final Logger log = LoggerFactory
95 .getLogger(NetconfTranslator.class);
Aaron Kruglikovbc26a522017-02-21 11:27:49 -080096
97 private NodeId localNodeId;
98
99 private static final String GET_CONFIG_MESSAGE_REGEX =
100 "<data>\n?\\s*(.*?)\n?\\s*</data>";
101 private static final int GET_CONFIG_CORE_MESSAGE_GROUP = 1;
102 private static final Pattern GET_CONFIG_CORE_MESSAGE_PATTERN =
103 Pattern.compile(GET_CONFIG_MESSAGE_REGEX, Pattern.DOTALL);
104 private static final String GET_CORE_MESSAGE_REGEX = "<data>\n?\\s*(.*?)\n?\\s*</data>";
105 private static final int GET_CORE_MESSAGE_GROUP = 1;
106 private static final Pattern GET_CORE_MESSAGE_PATTERN =
107 Pattern.compile(GET_CORE_MESSAGE_REGEX, Pattern.DOTALL);
108
109 private static final String NETCONF_1_0_BASE_NAMESPACE =
110 "urn:ietf:params:xml:ns:netconf:base:1.0";
111
112 private static final String GET_URI = "urn:ietf:params:xml:ns:yang:" +
113 "yrt-ietf-network:networks/network/node";
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530114 private static final String XML_ENCODING_SPECIFIER = "xml";
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800115 private static final String OP_SPECIFIER = "xc:operation";
116 private static final String REPLACE_OP_SPECIFIER = "replace";
117 private static final String DELETE_OP_SPECIFIER = "delete";
118 private static final String XMLNS_XC_SPECIFIER = "xmlns:xc";
119 private static final String XMLNS_SPECIFIER = "xmlns";
120
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700121 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800122 protected NetconfController netconfController;
123
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700124 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800125 protected YangRuntimeService yangRuntimeService;
126
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700127 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700128 protected SchemaContextProvider schemaContextProvider;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800129
130 @Activate
131 public void activate(ComponentContext context) {
132 log.info("Started");
133 }
134
135 @Deactivate
136 public void deactivate() {
137 log.info("Stopped");
138 }
139
140 @Override
141 public ResourceData getDeviceConfig(DeviceId deviceId) throws IOException {
142 NetconfSession session = getNetconfSession(deviceId);
143 /*FIXME "running" will be replaced with an enum once netconf supports multiple datastores.*/
Andrei Mihaescuac542ca2017-03-26 21:36:25 +0300144 String reply = session.getConfig(RUNNING);
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800145 Matcher protocolStripper = GET_CONFIG_CORE_MESSAGE_PATTERN.matcher(reply);
146 reply = protocolStripper.group(GET_CONFIG_CORE_MESSAGE_GROUP);
147 return yangRuntimeService.decode(
148 new DefaultCompositeStream(
149 null,
150 /*FIXME is UTF_8 the appropriate encoding? */
151 new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8))),
152 new DefaultRuntimeContext.Builder()
153 .setDataFormat(XML_ENCODING_SPECIFIER)
154 .addAnnotation(
155 new DefaultAnnotation(XMLNS_SPECIFIER,
156 NETCONF_1_0_BASE_NAMESPACE))
157 .build()).resourceData();
158 }
159
160 @Override
161 public boolean editDeviceConfig(DeviceId deviceId, ResourceData resourceData,
162 NetconfTranslator.OperationType operationType) throws IOException {
163 NetconfSession session = getNetconfSession(deviceId);
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700164 SchemaContext context = schemaContextProvider
165 .getSchemaContext(ResourceId.builder().addBranchPointSchema("/", null).build());
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800166 ResourceData modifiedPathResourceData = getResourceData(resourceData.resourceId(),
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530167 resourceData.dataNodes(),
168 new DefaultYangSerializerContext(context, null));
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800169 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) {
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530175 resourceId = getAnnotatedNodeResourceId(
176 resourceData.resourceId(), node);
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800177 }
178 if (resourceId != null) {
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530179 DefaultAnnotatedNodeInfo.Builder annotatedNodeInfo =
180 DefaultAnnotatedNodeInfo.builder();
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800181 annotatedNodeInfo.resourceId(resourceId);
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530182 annotatedNodeInfo.addAnnotation(
183 new DefaultAnnotation(
184 OP_SPECIFIER, operationType == OperationType.DELETE ?
185 DELETE_OP_SPECIFIER : REPLACE_OP_SPECIFIER));
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800186 compositeDataBuilder.addAnnotatedNodeInfo(annotatedNodeInfo.build());
187 }
188 }
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530189 CompositeStream config = yangRuntimeService.encode(
190 compositeDataBuilder.build(),
191 new DefaultRuntimeContext.Builder()
192 .setDataFormat(XML_ENCODING_SPECIFIER)
193 .addAnnotation(new DefaultAnnotation(
194 XMLNS_XC_SPECIFIER, NETCONF_1_0_BASE_NAMESPACE))
195 .build());
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800196 /* FIXME need to fix to string conversion. */
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530197
198 try {
199 String reply = session.requestSync(Utils.editConfig(streamToString(
200 config.resourceData())));
201 } catch (NetconfException e) {
202 log.error("failed to send a request sync", e);
203 return false;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800204 }
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530205 /* NOTE: a failure to edit is reflected as a NetconfException.*/
206 return true;
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800207 }
208
209 @Override
210 public ResourceData getDeviceState(DeviceId deviceId) throws IOException {
211 NetconfSession session = getNetconfSession(deviceId);
212 /*TODO the first parameter will come into use if get is required to support filters.*/
213 String reply = session.get(null, null);
214 Matcher protocolStripper = GET_CORE_MESSAGE_PATTERN.matcher(reply);
215 reply = protocolStripper.group(GET_CORE_MESSAGE_GROUP);
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530216 return yangRuntimeService.decode(
217 new DefaultCompositeStream(
218 null,
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800219 /*FIXME is UTF_8 the appropriate encoding? */
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530220 new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8))),
221 new DefaultRuntimeContext.Builder()
222 .setDataFormat(XML_ENCODING_SPECIFIER)
223 .addAnnotation(
224 new DefaultAnnotation(
225 XMLNS_SPECIFIER,
226 NETCONF_1_0_BASE_NAMESPACE))
227 .build()).resourceData();
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800228 /* NOTE: a failure to get is reflected as a NetconfException.*/
229 }
230
231 /**
232 * Returns a session for the specified deviceId if this node is its master,
233 * returns null otherwise.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530234 *
sangyun-han43c56702017-07-11 11:55:28 +0900235 * @param deviceId the id of node for which we wish to retrieve a session
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800236 * @return a NetconfSession with the specified node or null
237 */
238 private NetconfSession getNetconfSession(DeviceId deviceId) {
239 NetconfDevice device = netconfController.getNetconfDevice(deviceId);
240 checkNotNull(device, "The specified deviceId could not be found by the NETCONF controller.");
241 NetconfSession session = device.getSession();
242 checkNotNull(session, "A session could not be retrieved for the specified deviceId.");
243 return session;
244 }
245
246 /**
247 * Accepts a stream and converts it to a string.
248 *
249 * @param stream the stream to be converted
250 * @return a string with the same sequence of characters as the stream
251 * @throws IOException if reading from the stream fails
252 */
253 private String streamToString(InputStream stream) throws IOException {
254 BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
255 StringBuilder builder = new StringBuilder();
256
257 String nextLine = reader.readLine();
258 while (nextLine != null) {
259 builder.append(nextLine);
260 nextLine = reader.readLine();
261 }
262 return builder.toString();
263 }
264
265 /**
266 * Returns resource data having resource id as "/" and data node tree
267 * starting from "/" by creating data nodes for given resource id(parent
268 * node for given list of nodes) and list of child nodes.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530269 * <p>
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800270 * This api will be used in encode flow only.
271 *
272 * @param rid resource identifier till parent node
273 * @param nodes list of data nodes
274 * @param cont yang serializer context
275 * @return resource data.
276 */
277 public static ResourceData getResourceData(
278 ResourceId rid, List<DataNode> nodes, YangSerializerContext cont) {
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530279 if (rid == null) {
280 ResourceData.Builder resData = DefaultResourceData.builder();
281 for (DataNode node : nodes) {
282 resData.addDataNode(node);
283 }
284 return resData.build();
285 }
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800286 List<NodeKey> keys = rid.nodeKeys();
287 Iterator<NodeKey> it = keys.iterator();
288 DataNode.Builder dbr = SerializerHelper.initializeDataNode(cont);
289
290 // checking the resource id weather it is getting started from / or not
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800291
292 while (it.hasNext()) {
293 NodeKey nodekey = it.next();
294 SchemaId sid = nodekey.schemaId();
295 dbr = addDataNode(dbr, sid.name(), sid.namespace(),
296 null, null);
297 if (nodekey instanceof ListKey) {
298 for (KeyLeaf keyLeaf : ((ListKey) nodekey).keyLeafs()) {
299 String val;
300 if (keyLeaf.leafValue() == null) {
301 val = null;
302 } else {
303 val = keyLeaf.leafValAsString();
304 }
305 dbr = addDataNode(dbr, keyLeaf.leafSchema().name(),
306 sid.namespace(), val,
307 SINGLE_INSTANCE_LEAF_VALUE_NODE);
308 }
309 }
310 }
311
312 if (dbr instanceof LeafNode.Builder &&
Ray Milkey57add212018-01-16 13:04:42 -0800313 (nodes != null && !nodes.isEmpty())) {
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800314 //exception "leaf/leaf-list can not have child node"
315 }
316
317 if (nodes != null && !nodes.isEmpty()) {
318 // adding the parent node for given list of nodes
319 for (DataNode node : nodes) {
320 dbr = ((InnerNode.Builder) dbr).addNode(node);
321 }
322 }
Aaron Kruglikovd24dc982017-03-23 18:48:58 -0700323/*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 -0800324// while (dbr.parent() != null) {
325// dbr = SerializerHelper.exitDataNode(dbr);
326// }
327
328 ResourceData.Builder resData = DefaultResourceData.builder();
329
330 resData.addDataNode(dbr.build());
331 resData.resourceId(null);
332 return resData.build();
333 }
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530334
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800335 /**
336 * Returns resource id for annotated data node by adding resource id of top
337 * level data node to given resource id.
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530338 * <p>
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800339 * Annotation will be added to node based on the updated resource id.
340 * This api will be used in encode flow only.
341 *
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530342 * @param rid resource identifier till parent node
343 * @param node data node
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800344 * @return updated resource id.
345 */
346 public static ResourceId getAnnotatedNodeResourceId(ResourceId rid,
347 DataNode node) {
348
349 String val;
350 ResourceId.Builder rIdBldr = ResourceId.builder();
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530351 if (rid != null) {
352 try {
353 rIdBldr = rid.copyBuilder();
354 } catch (CloneNotSupportedException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -0800355 log.debug("clone not supported", e);
Bharat saraswalb0dbe6b2017-03-24 22:51:06 +0530356 }
357 } else {
358 rIdBldr.addBranchPointSchema("/", null);
Aaron Kruglikovbc26a522017-02-21 11:27:49 -0800359 }
360 DataNode.Type type = node.type();
361 NodeKey k = node.key();
362 SchemaId sid = k.schemaId();
363
364 switch (type) {
365
366 case MULTI_INSTANCE_LEAF_VALUE_NODE:
367 val = ((LeafListKey) k).value().toString();
368 rIdBldr.addLeafListBranchPoint(sid.name(), sid.namespace(), val);
369 break;
370
371 case MULTI_INSTANCE_NODE:
372 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
373// Preparing the list of key values for multiInstanceNode
374 for (KeyLeaf keyLeaf : ((ListKey) node.key()).keyLeafs()) {
375 val = keyLeaf.leafValAsString();
376 rIdBldr.addKeyLeaf(keyLeaf.leafSchema().name(), sid.namespace(), val);
377 }
378 break;
379 case SINGLE_INSTANCE_LEAF_VALUE_NODE:
380 case SINGLE_INSTANCE_NODE:
381 rIdBldr.addBranchPointSchema(sid.name(), sid.namespace());
382 break;
383
384 default:
385 throw new IllegalArgumentException();
386 }
387 return rIdBldr.build();
388 }
389}