blob: c559a0349a5a91a79887cd535faa4b1640fa4c90 [file] [log] [blame]
Andrea Campanella101417d2015-12-11 17:58:07 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Andrea Campanella101417d2015-12-11 17:58:07 -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
Yuta HIGUCHIe3ae8212017-04-20 10:18:41 -070017package org.onosproject.netconf.ctl.impl;
Andrea Campanella101417d2015-12-11 17:58:07 -080018
Andrea Campanella101417d2015-12-11 17:58:07 -080019import com.google.common.collect.Lists;
20import org.onosproject.netconf.NetconfDeviceInfo;
21import org.onosproject.netconf.NetconfDeviceOutputEvent;
22import org.onosproject.netconf.NetconfDeviceOutputEventListener;
23import org.onosproject.netconf.NetconfException;
24import org.slf4j.Logger;
25import org.slf4j.LoggerFactory;
26
Kamil Stasiak9f59f442017-05-02 11:02:24 +020027
Andrea Campanella101417d2015-12-11 17:58:07 -080028import java.io.BufferedReader;
Andrea Campanella101417d2015-12-11 17:58:07 -080029import java.io.InputStream;
Andrea Campanella101417d2015-12-11 17:58:07 -080030import java.io.OutputStream;
Sean Condon7347de92017-07-21 12:17:25 +010031import java.io.OutputStreamWriter;
32import java.nio.charset.StandardCharsets;
David K. Bainbridge9b582b02019-02-01 16:04:05 -080033import java.nio.channels.ClosedByInterruptException;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020034import java.io.InputStreamReader;
35import java.io.IOException;
36import java.io.UnsupportedEncodingException;
Andrea Campanella101417d2015-12-11 17:58:07 -080037import java.util.List;
Sean Condond2c8d472017-02-17 17:09:39 +000038import java.util.Map;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020039import java.util.ArrayList;
Andreas Papazoisd4712e22016-02-10 15:59:55 +020040import java.util.Optional;
Andrea Campanella101417d2015-12-11 17:58:07 -080041import java.util.concurrent.CompletableFuture;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020042import java.util.regex.MatchResult;
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -050043import java.util.regex.Matcher;
44import java.util.regex.Pattern;
Andrea Campanella101417d2015-12-11 17:58:07 -080045
46/**
47 * Thread that gets spawned each time a session is established and handles all the input
48 * and output from the session's streams to and from the NETCONF device the session is
49 * established with.
50 */
51public class NetconfStreamThread extends Thread implements NetconfStreamHandler {
52
53 private static final Logger log = LoggerFactory
54 .getLogger(NetconfStreamThread.class);
Andrea Campanella1311ea02016-03-04 17:51:25 -080055 private static final String HELLO = "<hello";
Andrea Campanella101417d2015-12-11 17:58:07 -080056 private static final String END_PATTERN = "]]>]]>";
57 private static final String RPC_REPLY = "rpc-reply";
58 private static final String RPC_ERROR = "rpc-error";
heisenbergb7017d72016-04-13 02:16:07 -070059 private static final String NOTIFICATION_LABEL = "<notification";
Andreas Papazoisd4712e22016-02-10 15:59:55 +020060 private static final String MESSAGE_ID = "message-id=";
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -050061 private static final Pattern MSGID_PATTERN = Pattern.compile(MESSAGE_ID + "\"(\\d+)\"");
Kamil Stasiak9f59f442017-05-02 11:02:24 +020062 private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n";
63 // pattern to verify whole Chunked-Message format
64 private static final Pattern CHUNKED_FRAMING_PATTERN =
65 Pattern.compile("(\\n#([1-9][0-9]*)\\n(.+))+\\n##\\n", Pattern.DOTALL);
Kamil Stasiak9f59f442017-05-02 11:02:24 +020066 private static final String CHUNKED_END_REGEX_PATTERN = "\n##\n";
67 // pattern to parse each chunk-size in ChunkedMessage chunk
68 private static final Pattern CHUNKED_SIZE_PATTERN = Pattern.compile("\\n#([1-9][0-9]*)\\n");
Kamil Stasiak9f59f442017-05-02 11:02:24 +020069 private static final char HASH_CHAR = '#';
Kamil Stasiak9f59f442017-05-02 11:02:24 +020070 private static final char LF_CHAR = '\n';
Andrea Campanella101417d2015-12-11 17:58:07 -080071
Sean Condon7347de92017-07-21 12:17:25 +010072 private OutputStreamWriter outputStream;
Andrea Campanellab029b9e2016-01-29 11:05:36 -080073 private final InputStream err;
74 private final InputStream in;
75 private NetconfDeviceInfo netconfDeviceInfo;
76 private NetconfSessionDelegate sessionDelegate;
77 private NetconfMessageState state;
helenyrwu0407c642016-06-09 12:01:30 -070078 private List<NetconfDeviceOutputEventListener> netconfDeviceEventListeners
79 = Lists.newCopyOnWriteArrayList();
80 private boolean enableNotifications = true;
Sean Condond2c8d472017-02-17 17:09:39 +000081 private Map<Integer, CompletableFuture<String>> replies;
Andrea Campanella101417d2015-12-11 17:58:07 -080082
83 public NetconfStreamThread(final InputStream in, final OutputStream out,
84 final InputStream err, NetconfDeviceInfo deviceInfo,
Sean Condond2c8d472017-02-17 17:09:39 +000085 NetconfSessionDelegate delegate,
86 Map<Integer, CompletableFuture<String>> replies) {
Andrea Campanellab029b9e2016-01-29 11:05:36 -080087 this.in = in;
88 this.err = err;
Sean Condon7347de92017-07-21 12:17:25 +010089 outputStream = new OutputStreamWriter(out, StandardCharsets.UTF_8);
Andrea Campanella101417d2015-12-11 17:58:07 -080090 netconfDeviceInfo = deviceInfo;
91 state = NetconfMessageState.NO_MATCHING_PATTERN;
92 sessionDelegate = delegate;
Sean Condond2c8d472017-02-17 17:09:39 +000093 this.replies = replies;
Andrea Campanella101417d2015-12-11 17:58:07 -080094 log.debug("Stream thread for device {} session started", deviceInfo);
95 start();
96 }
97
98 @Override
99 public CompletableFuture<String> sendMessage(String request) {
Sean Condond2c8d472017-02-17 17:09:39 +0000100 Optional<Integer> messageId = getMsgId(request);
101 return sendMessage(request, messageId.get());
102 }
103
104 @Override
105 public CompletableFuture<String> sendMessage(String request, int messageId) {
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800106 log.debug("Sending message {} to device {}", request, netconfDeviceInfo);
Sean Condond2c8d472017-02-17 17:09:39 +0000107 CompletableFuture<String> cf = new CompletableFuture<>();
108 replies.put(messageId, cf);
109
110 synchronized (outputStream) {
Sean Condon7347de92017-07-21 12:17:25 +0100111 try {
112 outputStream.write(request);
113 outputStream.flush();
114 } catch (IOException e) {
115 log.error("Writing to {} failed", netconfDeviceInfo, e);
116 cf.completeExceptionally(e);
117 }
Sean Condond2c8d472017-02-17 17:09:39 +0000118 }
119
120 return cf;
Andrea Campanella101417d2015-12-11 17:58:07 -0800121 }
122
123 public enum NetconfMessageState {
124
125 NO_MATCHING_PATTERN {
126 @Override
127 NetconfMessageState evaluateChar(char c) {
128 if (c == ']') {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800129 return FIRST_BRACKET;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200130 } else if (c == '\n') {
131 return FIRST_LF;
Andrea Campanella101417d2015-12-11 17:58:07 -0800132 } else {
133 return this;
134 }
135 }
136 },
Andrea Campanella1311ea02016-03-04 17:51:25 -0800137 FIRST_BRACKET {
Andrea Campanella101417d2015-12-11 17:58:07 -0800138 @Override
139 NetconfMessageState evaluateChar(char c) {
140 if (c == ']') {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800141 return SECOND_BRACKET;
Andrea Campanella101417d2015-12-11 17:58:07 -0800142 } else {
143 return NO_MATCHING_PATTERN;
144 }
145 }
146 },
Andrea Campanella1311ea02016-03-04 17:51:25 -0800147 SECOND_BRACKET {
Andrea Campanella101417d2015-12-11 17:58:07 -0800148 @Override
149 NetconfMessageState evaluateChar(char c) {
150 if (c == '>') {
151 return FIRST_BIGGER;
152 } else {
153 return NO_MATCHING_PATTERN;
154 }
155 }
156 },
157 FIRST_BIGGER {
158 @Override
159 NetconfMessageState evaluateChar(char c) {
160 if (c == ']') {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800161 return THIRD_BRACKET;
Andrea Campanella101417d2015-12-11 17:58:07 -0800162 } else {
163 return NO_MATCHING_PATTERN;
164 }
165 }
166 },
Andrea Campanella1311ea02016-03-04 17:51:25 -0800167 THIRD_BRACKET {
Andrea Campanella101417d2015-12-11 17:58:07 -0800168 @Override
169 NetconfMessageState evaluateChar(char c) {
170 if (c == ']') {
171 return ENDING_BIGGER;
172 } else {
173 return NO_MATCHING_PATTERN;
174 }
175 }
176 },
177 ENDING_BIGGER {
178 @Override
179 NetconfMessageState evaluateChar(char c) {
180 if (c == '>') {
181 return END_PATTERN;
182 } else {
183 return NO_MATCHING_PATTERN;
184 }
185 }
186 },
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200187 FIRST_LF {
188 @Override
189 NetconfMessageState evaluateChar(char c) {
190 if (c == '#') {
191 return FIRST_HASH;
192 } else if (c == ']') {
193 return FIRST_BRACKET;
194 } else if (c == '\n') {
195 return this;
196 } else {
197 return NO_MATCHING_PATTERN;
198 }
199 }
200 },
201 FIRST_HASH {
202 @Override
203 NetconfMessageState evaluateChar(char c) {
204 if (c == '#') {
205 return SECOND_HASH;
206 } else {
207 return NO_MATCHING_PATTERN;
208 }
209 }
210 },
211 SECOND_HASH {
212 @Override
213 NetconfMessageState evaluateChar(char c) {
214 if (c == '\n') {
215 return END_CHUNKED_PATTERN;
216 } else {
217 return NO_MATCHING_PATTERN;
218 }
219 }
220 },
221 END_CHUNKED_PATTERN {
222 @Override
223 NetconfMessageState evaluateChar(char c) {
224 return NO_MATCHING_PATTERN;
225 }
226 },
Andrea Campanella101417d2015-12-11 17:58:07 -0800227 END_PATTERN {
228 @Override
229 NetconfMessageState evaluateChar(char c) {
230 return NO_MATCHING_PATTERN;
231 }
232 };
233
234 abstract NetconfMessageState evaluateChar(char c);
235 }
236
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700237 @Override
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800238 public void run() {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200239 BufferedReader bufferReader = null;
240 while (bufferReader == null) {
Andrea Campanella101417d2015-12-11 17:58:07 -0800241 try {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200242 bufferReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
243 } catch (UnsupportedEncodingException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -0800244 throw new IllegalStateException(e);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200245 }
246 }
247
248 try {
249 boolean socketClosed = false;
250 StringBuilder deviceReplyBuilder = new StringBuilder();
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800251 while (!socketClosed && !this.isInterrupted()) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200252 int cInt = bufferReader.read();
253 if (cInt == -1) {
254 log.debug("Netconf device {} sent error char in session," +
Andrea Campanella59227c32019-01-07 14:52:35 +0100255 " will need to be reopened", netconfDeviceInfo);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200256 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
257 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
258 null, null, Optional.of(-1), netconfDeviceInfo);
259 netconfDeviceEventListeners.forEach(
260 listener -> listener.event(event));
261 socketClosed = true;
262 log.debug("Netconf device {} ERROR cInt == -1 socketClosed = true", netconfDeviceInfo);
263 }
264 char c = (char) cInt;
265 state = state.evaluateChar(c);
266 deviceReplyBuilder.append(c);
267 if (state == NetconfMessageState.END_PATTERN) {
268 String deviceReply = deviceReplyBuilder.toString();
269 if (deviceReply.equals(END_PATTERN)) {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800270 socketClosed = true;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200271 close(deviceReply);
272 } else {
273 deviceReply = deviceReply.replace(END_PATTERN, "");
274 dealWithReply(deviceReply);
275 deviceReplyBuilder.setLength(0);
Andrea Campanella101417d2015-12-11 17:58:07 -0800276 }
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200277 } else if (state == NetconfMessageState.END_CHUNKED_PATTERN) {
278 String deviceReply = deviceReplyBuilder.toString();
279 if (!validateChunkedFraming(deviceReply)) {
280 log.debug("Netconf device {} send badly framed message {}",
281 netconfDeviceInfo, deviceReply);
282 socketClosed = true;
283 close(deviceReply);
284 } else {
285 deviceReply = deviceReply.replaceAll(MSGLEN_REGEX_PATTERN, "");
286 deviceReply = deviceReply.replaceAll(CHUNKED_END_REGEX_PATTERN, "");
287 dealWithReply(deviceReply);
288 deviceReplyBuilder.setLength(0);
Andrea Campanella101417d2015-12-11 17:58:07 -0800289 }
290 }
Andrea Campanella101417d2015-12-11 17:58:07 -0800291 }
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800292 } catch (ClosedByInterruptException i) {
293 log.debug("Connection to device {} was terminated on request", netconfDeviceInfo.toString());
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200294 } catch (IOException e) {
295 log.warn("Error in reading from the session for device {} ", netconfDeviceInfo, e);
Ray Milkey986a47a2018-01-25 11:38:51 -0800296 throw new IllegalStateException(new NetconfException("Error in reading from the session for device {}" +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200297 netconfDeviceInfo, e));
298 //TODO should we send a socket closed message to listeners ?
299 }
300 }
301
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800302 public void close() {
303 close("on request");
304 }
305
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200306 private void close(String deviceReply) {
307 log.debug("Netconf device {} socketClosed = true DEVICE_UNREGISTERED {}",
308 netconfDeviceInfo, deviceReply);
309 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
310 NetconfDeviceOutputEvent.Type.DEVICE_UNREGISTERED,
311 null, null, Optional.of(-1), netconfDeviceInfo);
312 netconfDeviceEventListeners.forEach(
313 listener -> listener.event(event));
314 this.interrupt();
315 }
316
317 private void dealWithReply(String deviceReply) {
318 if (deviceReply.contains(RPC_REPLY) ||
319 deviceReply.contains(RPC_ERROR) ||
320 deviceReply.contains(HELLO)) {
321 log.debug("Netconf device {} sessionDelegate.notify() DEVICE_REPLY {} {}",
322 netconfDeviceInfo, getMsgId(deviceReply), deviceReply);
323 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
324 NetconfDeviceOutputEvent.Type.DEVICE_REPLY,
325 null, deviceReply, getMsgId(deviceReply), netconfDeviceInfo);
326 sessionDelegate.notify(event);
327 netconfDeviceEventListeners.forEach(
328 listener -> listener.event(event));
329 } else if (deviceReply.contains(NOTIFICATION_LABEL)) {
330 log.debug("Netconf device {} DEVICE_NOTIFICATION {} {} {}",
331 netconfDeviceInfo, enableNotifications,
332 getMsgId(deviceReply), deviceReply);
333 if (enableNotifications) {
334 log.debug("dispatching to {} listeners", netconfDeviceEventListeners.size());
335 final String finalDeviceReply = deviceReply;
336 netconfDeviceEventListeners.forEach(
337 listener -> listener.event(new NetconfDeviceOutputEvent(
338 NetconfDeviceOutputEvent.Type.DEVICE_NOTIFICATION,
339 null, finalDeviceReply, getMsgId(finalDeviceReply),
340 netconfDeviceInfo)));
341 }
342 } else {
343 log.debug("Error on reply from device {} {}", netconfDeviceInfo, deviceReply);
344 }
345 }
346
347 static boolean validateChunkedFraming(String reply) {
348 Matcher matcher = CHUNKED_FRAMING_PATTERN.matcher(reply);
349 if (!matcher.matches()) {
350 log.debug("Error on reply {}", reply);
351 return false;
352 }
353 Matcher chunkM = CHUNKED_SIZE_PATTERN.matcher(reply);
354 List<MatchResult> chunks = new ArrayList<>();
355 String chunkdataStr = "";
356 while (chunkM.find()) {
357 chunks.add(chunkM.toMatchResult());
358 // extract chunk-data (and later) in bytes
359 int bytes = Integer.parseInt(chunkM.group(1));
360 byte[] chunkdata = reply.substring(chunkM.end()).getBytes(StandardCharsets.UTF_8);
361 if (bytes > chunkdata.length) {
362 log.debug("Error on reply - wrong chunk size {}", reply);
363 return false;
364 }
365 //check if after chunk-size bytes there is next chunk or message ending
366 if (chunkdata[bytes] != LF_CHAR || chunkdata[bytes + 1] != HASH_CHAR) {
367 log.debug("Error on reply - wrong chunk size {}", reply);
368 return false;
369 }
370 // convert (only) chunk-data part into String
371 chunkdataStr = new String(chunkdata, 0, bytes, StandardCharsets.UTF_8);
372 // skip chunk-data part from next match
373 chunkM.region(chunkM.end() + chunkdataStr.length(), reply.length());
374 }
375 if (!"\n##\n".equals(reply.substring(chunks.get(chunks.size() - 1).end() + chunkdataStr.length()))) {
376 log.debug("Error on reply {}", reply);
377 return false;
378 }
379 return true;
Andrea Campanella101417d2015-12-11 17:58:07 -0800380 }
381
Sean Condond2c8d472017-02-17 17:09:39 +0000382 protected static Optional<Integer> getMsgId(String reply) {
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -0500383 Matcher matcher = MSGID_PATTERN.matcher(reply);
384 if (matcher.find()) {
Sean Condon7347de92017-07-21 12:17:25 +0100385 try {
386 return Optional.of(Integer.valueOf(matcher.group(1)));
387 } catch (NumberFormatException e) {
388 log.warn("Failed to parse message-id from {}", matcher.group(), e);
389 }
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -0500390 }
391 if (reply.contains(HELLO)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700392 return Optional.of(-1);
Andrea Campanella101417d2015-12-11 17:58:07 -0800393 }
Andrea Campanella1311ea02016-03-04 17:51:25 -0800394 return Optional.empty();
Andrea Campanella101417d2015-12-11 17:58:07 -0800395 }
396
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700397 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800398 public void addDeviceEventListener(NetconfDeviceOutputEventListener listener) {
399 if (!netconfDeviceEventListeners.contains(listener)) {
400 netconfDeviceEventListeners.add(listener);
401 }
402 }
403
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700404 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800405 public void removeDeviceEventListener(NetconfDeviceOutputEventListener listener) {
406 netconfDeviceEventListeners.remove(listener);
407 }
helenyrwu0407c642016-06-09 12:01:30 -0700408
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700409 @Override
helenyrwu0407c642016-06-09 12:01:30 -0700410 public void setEnableNotifications(boolean enableNotifications) {
411 this.enableNotifications = enableNotifications;
412 }
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800413}