blob: 55bd659de63c07ee154f2bb85e8e7a9766ec5c98 [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 Campanellac535b672019-02-25 16:25:35 +010071 protected static final String ON_REQUEST = "on request";
Andrea Campanella101417d2015-12-11 17:58:07 -080072
Sean Condon7347de92017-07-21 12:17:25 +010073 private OutputStreamWriter outputStream;
Andrea Campanellab029b9e2016-01-29 11:05:36 -080074 private final InputStream err;
75 private final InputStream in;
76 private NetconfDeviceInfo netconfDeviceInfo;
77 private NetconfSessionDelegate sessionDelegate;
78 private NetconfMessageState state;
helenyrwu0407c642016-06-09 12:01:30 -070079 private List<NetconfDeviceOutputEventListener> netconfDeviceEventListeners
80 = Lists.newCopyOnWriteArrayList();
81 private boolean enableNotifications = true;
Sean Condond2c8d472017-02-17 17:09:39 +000082 private Map<Integer, CompletableFuture<String>> replies;
Andrea Campanella101417d2015-12-11 17:58:07 -080083
84 public NetconfStreamThread(final InputStream in, final OutputStream out,
85 final InputStream err, NetconfDeviceInfo deviceInfo,
Sean Condond2c8d472017-02-17 17:09:39 +000086 NetconfSessionDelegate delegate,
87 Map<Integer, CompletableFuture<String>> replies) {
Andrea Campanellab029b9e2016-01-29 11:05:36 -080088 this.in = in;
89 this.err = err;
Sean Condon7347de92017-07-21 12:17:25 +010090 outputStream = new OutputStreamWriter(out, StandardCharsets.UTF_8);
Andrea Campanella101417d2015-12-11 17:58:07 -080091 netconfDeviceInfo = deviceInfo;
92 state = NetconfMessageState.NO_MATCHING_PATTERN;
93 sessionDelegate = delegate;
Sean Condond2c8d472017-02-17 17:09:39 +000094 this.replies = replies;
Andrea Campanella101417d2015-12-11 17:58:07 -080095 log.debug("Stream thread for device {} session started", deviceInfo);
96 start();
97 }
98
99 @Override
100 public CompletableFuture<String> sendMessage(String request) {
Sean Condond2c8d472017-02-17 17:09:39 +0000101 Optional<Integer> messageId = getMsgId(request);
102 return sendMessage(request, messageId.get());
103 }
104
105 @Override
106 public CompletableFuture<String> sendMessage(String request, int messageId) {
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800107 log.debug("Sending message {} to device {}", request, netconfDeviceInfo);
Sean Condond2c8d472017-02-17 17:09:39 +0000108 CompletableFuture<String> cf = new CompletableFuture<>();
109 replies.put(messageId, cf);
110
111 synchronized (outputStream) {
Sean Condon7347de92017-07-21 12:17:25 +0100112 try {
113 outputStream.write(request);
114 outputStream.flush();
115 } catch (IOException e) {
116 log.error("Writing to {} failed", netconfDeviceInfo, e);
117 cf.completeExceptionally(e);
118 }
Sean Condond2c8d472017-02-17 17:09:39 +0000119 }
120
121 return cf;
Andrea Campanella101417d2015-12-11 17:58:07 -0800122 }
123
124 public enum NetconfMessageState {
125
126 NO_MATCHING_PATTERN {
127 @Override
128 NetconfMessageState evaluateChar(char c) {
129 if (c == ']') {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800130 return FIRST_BRACKET;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200131 } else if (c == '\n') {
132 return FIRST_LF;
Andrea Campanella101417d2015-12-11 17:58:07 -0800133 } else {
134 return this;
135 }
136 }
137 },
Andrea Campanella1311ea02016-03-04 17:51:25 -0800138 FIRST_BRACKET {
Andrea Campanella101417d2015-12-11 17:58:07 -0800139 @Override
140 NetconfMessageState evaluateChar(char c) {
141 if (c == ']') {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800142 return SECOND_BRACKET;
Andrea Campanella101417d2015-12-11 17:58:07 -0800143 } else {
144 return NO_MATCHING_PATTERN;
145 }
146 }
147 },
Andrea Campanella1311ea02016-03-04 17:51:25 -0800148 SECOND_BRACKET {
Andrea Campanella101417d2015-12-11 17:58:07 -0800149 @Override
150 NetconfMessageState evaluateChar(char c) {
151 if (c == '>') {
152 return FIRST_BIGGER;
153 } else {
154 return NO_MATCHING_PATTERN;
155 }
156 }
157 },
158 FIRST_BIGGER {
159 @Override
160 NetconfMessageState evaluateChar(char c) {
161 if (c == ']') {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800162 return THIRD_BRACKET;
Andrea Campanella101417d2015-12-11 17:58:07 -0800163 } else {
164 return NO_MATCHING_PATTERN;
165 }
166 }
167 },
Andrea Campanella1311ea02016-03-04 17:51:25 -0800168 THIRD_BRACKET {
Andrea Campanella101417d2015-12-11 17:58:07 -0800169 @Override
170 NetconfMessageState evaluateChar(char c) {
171 if (c == ']') {
172 return ENDING_BIGGER;
173 } else {
174 return NO_MATCHING_PATTERN;
175 }
176 }
177 },
178 ENDING_BIGGER {
179 @Override
180 NetconfMessageState evaluateChar(char c) {
181 if (c == '>') {
182 return END_PATTERN;
183 } else {
184 return NO_MATCHING_PATTERN;
185 }
186 }
187 },
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200188 FIRST_LF {
189 @Override
190 NetconfMessageState evaluateChar(char c) {
191 if (c == '#') {
192 return FIRST_HASH;
193 } else if (c == ']') {
194 return FIRST_BRACKET;
195 } else if (c == '\n') {
196 return this;
197 } else {
198 return NO_MATCHING_PATTERN;
199 }
200 }
201 },
202 FIRST_HASH {
203 @Override
204 NetconfMessageState evaluateChar(char c) {
205 if (c == '#') {
206 return SECOND_HASH;
207 } else {
208 return NO_MATCHING_PATTERN;
209 }
210 }
211 },
212 SECOND_HASH {
213 @Override
214 NetconfMessageState evaluateChar(char c) {
215 if (c == '\n') {
216 return END_CHUNKED_PATTERN;
217 } else {
218 return NO_MATCHING_PATTERN;
219 }
220 }
221 },
222 END_CHUNKED_PATTERN {
223 @Override
224 NetconfMessageState evaluateChar(char c) {
225 return NO_MATCHING_PATTERN;
226 }
227 },
Andrea Campanella101417d2015-12-11 17:58:07 -0800228 END_PATTERN {
229 @Override
230 NetconfMessageState evaluateChar(char c) {
231 return NO_MATCHING_PATTERN;
232 }
233 };
234
235 abstract NetconfMessageState evaluateChar(char c);
236 }
237
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700238 @Override
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800239 public void run() {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200240 BufferedReader bufferReader = null;
241 while (bufferReader == null) {
Andrea Campanella101417d2015-12-11 17:58:07 -0800242 try {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200243 bufferReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
244 } catch (UnsupportedEncodingException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -0800245 throw new IllegalStateException(e);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200246 }
247 }
248
249 try {
250 boolean socketClosed = false;
251 StringBuilder deviceReplyBuilder = new StringBuilder();
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800252 while (!socketClosed && !this.isInterrupted()) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200253 int cInt = bufferReader.read();
254 if (cInt == -1) {
255 log.debug("Netconf device {} sent error char in session," +
Andrea Campanella59227c32019-01-07 14:52:35 +0100256 " will need to be reopened", netconfDeviceInfo);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200257 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
258 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
259 null, null, Optional.of(-1), netconfDeviceInfo);
260 netconfDeviceEventListeners.forEach(
261 listener -> listener.event(event));
262 socketClosed = true;
263 log.debug("Netconf device {} ERROR cInt == -1 socketClosed = true", netconfDeviceInfo);
264 }
265 char c = (char) cInt;
266 state = state.evaluateChar(c);
267 deviceReplyBuilder.append(c);
268 if (state == NetconfMessageState.END_PATTERN) {
269 String deviceReply = deviceReplyBuilder.toString();
270 if (deviceReply.equals(END_PATTERN)) {
Andrea Campanella1311ea02016-03-04 17:51:25 -0800271 socketClosed = true;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200272 close(deviceReply);
273 } else {
274 deviceReply = deviceReply.replace(END_PATTERN, "");
275 dealWithReply(deviceReply);
276 deviceReplyBuilder.setLength(0);
Andrea Campanella101417d2015-12-11 17:58:07 -0800277 }
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200278 } else if (state == NetconfMessageState.END_CHUNKED_PATTERN) {
279 String deviceReply = deviceReplyBuilder.toString();
280 if (!validateChunkedFraming(deviceReply)) {
281 log.debug("Netconf device {} send badly framed message {}",
282 netconfDeviceInfo, deviceReply);
283 socketClosed = true;
284 close(deviceReply);
285 } else {
286 deviceReply = deviceReply.replaceAll(MSGLEN_REGEX_PATTERN, "");
287 deviceReply = deviceReply.replaceAll(CHUNKED_END_REGEX_PATTERN, "");
288 dealWithReply(deviceReply);
289 deviceReplyBuilder.setLength(0);
Andrea Campanella101417d2015-12-11 17:58:07 -0800290 }
291 }
Andrea Campanella101417d2015-12-11 17:58:07 -0800292 }
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800293 } catch (ClosedByInterruptException i) {
294 log.debug("Connection to device {} was terminated on request", netconfDeviceInfo.toString());
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200295 } catch (IOException e) {
296 log.warn("Error in reading from the session for device {} ", netconfDeviceInfo, e);
Ray Milkey986a47a2018-01-25 11:38:51 -0800297 throw new IllegalStateException(new NetconfException("Error in reading from the session for device {}" +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200298 netconfDeviceInfo, e));
299 //TODO should we send a socket closed message to listeners ?
300 }
301 }
302
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800303 public void close() {
Andrea Campanellac535b672019-02-25 16:25:35 +0100304 close(ON_REQUEST);
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800305 }
306
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200307 private void close(String deviceReply) {
308 log.debug("Netconf device {} socketClosed = true DEVICE_UNREGISTERED {}",
309 netconfDeviceInfo, deviceReply);
Andrea Campanellac535b672019-02-25 16:25:35 +0100310 if (!deviceReply.equals(ON_REQUEST)) {
311 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
312 NetconfDeviceOutputEvent.Type.DEVICE_UNREGISTERED,
313 null, null, Optional.of(-1), netconfDeviceInfo);
314 netconfDeviceEventListeners.forEach(
315 listener -> listener.event(event));
316 }
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200317 this.interrupt();
318 }
319
320 private void dealWithReply(String deviceReply) {
321 if (deviceReply.contains(RPC_REPLY) ||
322 deviceReply.contains(RPC_ERROR) ||
323 deviceReply.contains(HELLO)) {
324 log.debug("Netconf device {} sessionDelegate.notify() DEVICE_REPLY {} {}",
325 netconfDeviceInfo, getMsgId(deviceReply), deviceReply);
326 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
327 NetconfDeviceOutputEvent.Type.DEVICE_REPLY,
328 null, deviceReply, getMsgId(deviceReply), netconfDeviceInfo);
329 sessionDelegate.notify(event);
330 netconfDeviceEventListeners.forEach(
331 listener -> listener.event(event));
332 } else if (deviceReply.contains(NOTIFICATION_LABEL)) {
333 log.debug("Netconf device {} DEVICE_NOTIFICATION {} {} {}",
334 netconfDeviceInfo, enableNotifications,
335 getMsgId(deviceReply), deviceReply);
336 if (enableNotifications) {
337 log.debug("dispatching to {} listeners", netconfDeviceEventListeners.size());
338 final String finalDeviceReply = deviceReply;
339 netconfDeviceEventListeners.forEach(
340 listener -> listener.event(new NetconfDeviceOutputEvent(
341 NetconfDeviceOutputEvent.Type.DEVICE_NOTIFICATION,
342 null, finalDeviceReply, getMsgId(finalDeviceReply),
343 netconfDeviceInfo)));
344 }
345 } else {
346 log.debug("Error on reply from device {} {}", netconfDeviceInfo, deviceReply);
347 }
348 }
349
350 static boolean validateChunkedFraming(String reply) {
351 Matcher matcher = CHUNKED_FRAMING_PATTERN.matcher(reply);
352 if (!matcher.matches()) {
353 log.debug("Error on reply {}", reply);
354 return false;
355 }
356 Matcher chunkM = CHUNKED_SIZE_PATTERN.matcher(reply);
357 List<MatchResult> chunks = new ArrayList<>();
358 String chunkdataStr = "";
359 while (chunkM.find()) {
360 chunks.add(chunkM.toMatchResult());
361 // extract chunk-data (and later) in bytes
362 int bytes = Integer.parseInt(chunkM.group(1));
363 byte[] chunkdata = reply.substring(chunkM.end()).getBytes(StandardCharsets.UTF_8);
364 if (bytes > chunkdata.length) {
365 log.debug("Error on reply - wrong chunk size {}", reply);
366 return false;
367 }
368 //check if after chunk-size bytes there is next chunk or message ending
369 if (chunkdata[bytes] != LF_CHAR || chunkdata[bytes + 1] != HASH_CHAR) {
370 log.debug("Error on reply - wrong chunk size {}", reply);
371 return false;
372 }
373 // convert (only) chunk-data part into String
374 chunkdataStr = new String(chunkdata, 0, bytes, StandardCharsets.UTF_8);
375 // skip chunk-data part from next match
376 chunkM.region(chunkM.end() + chunkdataStr.length(), reply.length());
377 }
378 if (!"\n##\n".equals(reply.substring(chunks.get(chunks.size() - 1).end() + chunkdataStr.length()))) {
379 log.debug("Error on reply {}", reply);
380 return false;
381 }
382 return true;
Andrea Campanella101417d2015-12-11 17:58:07 -0800383 }
384
Sean Condond2c8d472017-02-17 17:09:39 +0000385 protected static Optional<Integer> getMsgId(String reply) {
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -0500386 Matcher matcher = MSGID_PATTERN.matcher(reply);
387 if (matcher.find()) {
Sean Condon7347de92017-07-21 12:17:25 +0100388 try {
389 return Optional.of(Integer.valueOf(matcher.group(1)));
390 } catch (NumberFormatException e) {
391 log.warn("Failed to parse message-id from {}", matcher.group(), e);
392 }
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -0500393 }
394 if (reply.contains(HELLO)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700395 return Optional.of(-1);
Andrea Campanella101417d2015-12-11 17:58:07 -0800396 }
Andrea Campanella1311ea02016-03-04 17:51:25 -0800397 return Optional.empty();
Andrea Campanella101417d2015-12-11 17:58:07 -0800398 }
399
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700400 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800401 public void addDeviceEventListener(NetconfDeviceOutputEventListener listener) {
402 if (!netconfDeviceEventListeners.contains(listener)) {
403 netconfDeviceEventListeners.add(listener);
404 }
405 }
406
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700407 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800408 public void removeDeviceEventListener(NetconfDeviceOutputEventListener listener) {
409 netconfDeviceEventListeners.remove(listener);
410 }
helenyrwu0407c642016-06-09 12:01:30 -0700411
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700412 @Override
helenyrwu0407c642016-06-09 12:01:30 -0700413 public void setEnableNotifications(boolean enableNotifications) {
414 this.enableNotifications = enableNotifications;
415 }
David K. Bainbridge9b582b02019-02-01 16:04:05 -0800416}