blob: abdd3771a98286bae27e707fafff6defc299e409 [file] [log] [blame]
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07003 *
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.ctl.impl;
18
19import com.google.common.annotations.Beta;
20import com.google.common.base.MoreObjects;
21import com.google.common.base.Objects;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020022import com.google.common.collect.ImmutableList;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070023import com.google.common.collect.ImmutableSet;
24import org.apache.sshd.client.SshClient;
25import org.apache.sshd.client.channel.ClientChannel;
26import org.apache.sshd.client.future.ConnectFuture;
27import org.apache.sshd.client.future.OpenFuture;
28import org.apache.sshd.client.session.ClientSession;
Sean Condon7347de92017-07-21 12:17:25 +010029import org.apache.sshd.common.FactoryManager;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070030import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -070031import org.onosproject.netconf.DatastoreId;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070032import org.onosproject.netconf.NetconfDeviceInfo;
33import org.onosproject.netconf.NetconfDeviceOutputEvent;
34import org.onosproject.netconf.NetconfDeviceOutputEvent.Type;
35import org.onosproject.netconf.NetconfDeviceOutputEventListener;
36import org.onosproject.netconf.NetconfException;
37import org.onosproject.netconf.NetconfSession;
38import org.onosproject.netconf.NetconfSessionFactory;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070039import org.slf4j.Logger;
40import org.slf4j.LoggerFactory;
Yuta HIGUCHI15677982017-08-16 15:50:29 -070041
42import static java.nio.charset.StandardCharsets.UTF_8;
43
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070044import java.io.IOException;
45import java.nio.ByteBuffer;
46import java.nio.CharBuffer;
47import java.nio.charset.StandardCharsets;
48import java.security.KeyFactory;
49import java.security.KeyPair;
50import java.security.NoSuchAlgorithmException;
51import java.security.PublicKey;
52import java.security.spec.InvalidKeySpecException;
53import java.security.spec.X509EncodedKeySpec;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020054import java.util.LinkedHashSet;
55import java.util.Map;
56import java.util.Set;
57import java.util.List;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070058import java.util.Collection;
59import java.util.Collections;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070060import java.util.Optional;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020061import java.util.ArrayList;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070062import java.util.concurrent.CompletableFuture;
63import java.util.concurrent.ConcurrentHashMap;
64import java.util.concurrent.CopyOnWriteArrayList;
65import java.util.concurrent.ExecutionException;
66import java.util.concurrent.TimeUnit;
67import java.util.concurrent.TimeoutException;
68import java.util.concurrent.atomic.AtomicInteger;
69import java.util.regex.Matcher;
70import java.util.regex.Pattern;
71
72/**
73 * Implementation of a NETCONF session to talk to a device.
74 */
75public class NetconfSessionMinaImpl implements NetconfSession {
76
77 private static final Logger log = LoggerFactory
78 .getLogger(NetconfSessionMinaImpl.class);
79
80 private static final String ENDPATTERN = "]]>]]>";
81 private static final String MESSAGE_ID_STRING = "message-id";
82 private static final String HELLO = "<hello";
83 private static final String NEW_LINE = "\n";
84 private static final String END_OF_RPC_OPEN_TAG = "\">";
85 private static final String EQUAL = "=";
86 private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"";
87 private static final String RPC_OPEN = "<rpc ";
88 private static final String RPC_CLOSE = "</rpc>";
89 private static final String GET_OPEN = "<get>";
90 private static final String GET_CLOSE = "</get>";
91 private static final String WITH_DEFAULT_OPEN = "<with-defaults ";
92 private static final String WITH_DEFAULT_CLOSE = "</with-defaults>";
93 private static final String DEFAULT_OPERATION_OPEN = "<default-operation>";
94 private static final String DEFAULT_OPERATION_CLOSE = "</default-operation>";
95 private static final String SUBTREE_FILTER_OPEN = "<filter type=\"subtree\">";
96 private static final String SUBTREE_FILTER_CLOSE = "</filter>";
97 private static final String EDIT_CONFIG_OPEN = "<edit-config>";
98 private static final String EDIT_CONFIG_CLOSE = "</edit-config>";
99 private static final String TARGET_OPEN = "<target>";
100 private static final String TARGET_CLOSE = "</target>";
101 private static final String CONFIG_OPEN = "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
102 private static final String CONFIG_CLOSE = "</config>";
103 private static final String XML_HEADER =
104 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
105 private static final String NETCONF_BASE_NAMESPACE =
106 "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"";
107 private static final String NETCONF_WITH_DEFAULTS_NAMESPACE =
108 "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\"";
109 private static final String SUBSCRIPTION_SUBTREE_FILTER_OPEN =
110 "<filter xmlns:base10=\"urn:ietf:params:xml:ns:netconf:base:1.0\" base10:type=\"subtree\">";
111
112 private static final String INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0";
113
114 private static final String CAPABILITY_REGEX = "<capability>\\s*(.*?)\\s*</capability>";
115 private static final Pattern CAPABILITY_REGEX_PATTERN = Pattern.compile(CAPABILITY_REGEX);
116
117 private static final String SESSION_ID_REGEX = "<session-id>\\s*(.*?)\\s*</session-id>";
118 private static final Pattern SESSION_ID_REGEX_PATTERN = Pattern.compile(SESSION_ID_REGEX);
119 private static final String RSA = "RSA";
120 private static final String DSA = "DSA";
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200121 private static final String HASH = "#";
122 private static final String LF = "\n";
123 private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n";
124 private static final String NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0";
125 private static final String NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1";
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700126
127 private String sessionID;
128 private final AtomicInteger messageIdInteger = new AtomicInteger(1);
129 protected final NetconfDeviceInfo deviceInfo;
130 private Iterable<String> onosCapabilities =
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200131 ImmutableList.of(NETCONF_10_CAPABILITY, NETCONF_11_CAPABILITY);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700132
133 /* NOTE: the "serverHelloResponseOld" is deprecated in 1.10.0 and should eventually be removed */
134 @Deprecated
135 private String serverHelloResponseOld;
136 private final Set<String> deviceCapabilities = new LinkedHashSet<>();
137 private NetconfStreamHandler streamHandler;
138 private Map<Integer, CompletableFuture<String>> replies;
Sean Condon7347de92017-07-21 12:17:25 +0100139 private List<String> errorReplies; // Not sure why we need this?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700140 private boolean subscriptionConnected = false;
141 private String notificationFilterSchema = null;
142
143 private final Collection<NetconfDeviceOutputEventListener> primaryListeners =
144 new CopyOnWriteArrayList<>();
145 private final Collection<NetconfSession> children =
146 new CopyOnWriteArrayList<>();
147
Sean Condon54d82432017-07-26 22:27:25 +0100148 private int connectTimeout;
149 private int replyTimeout;
150 private int idleTimeout;
151
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700152
153 private ClientChannel channel = null;
154 private ClientSession session = null;
155 private SshClient client = null;
156
157
158 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
159 this.deviceInfo = deviceInfo;
160 replies = new ConcurrentHashMap<>();
161 errorReplies = new ArrayList<>();
Sean Condon54d82432017-07-26 22:27:25 +0100162
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700163 startConnection();
164 }
165
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200166 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo, List<String> capabilities) throws NetconfException {
167 this.deviceInfo = deviceInfo;
168 replies = new ConcurrentHashMap<>();
169 errorReplies = new ArrayList<>();
170 setOnosCapabilities(capabilities);
171 startConnection();
172 }
173
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700174 private void startConnection() throws NetconfException {
Sean Condon54d82432017-07-26 22:27:25 +0100175 connectTimeout = deviceInfo.getConnectTimeoutSec().orElse(
176 NetconfControllerImpl.netconfConnectTimeout);
177 replyTimeout = deviceInfo.getReplyTimeoutSec().orElse(
178 NetconfControllerImpl.netconfReplyTimeout);
179 idleTimeout = deviceInfo.getIdleTimeoutSec().orElse(
180 NetconfControllerImpl.netconfIdleTimeout);
181 log.info("Connecting to {} with timeouts C:{}, R:{}, I:{}", deviceInfo,
182 connectTimeout, replyTimeout, idleTimeout);
183
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700184 try {
185 startClient();
186 } catch (IOException e) {
187 throw new NetconfException("Failed to establish SSH with device " + deviceInfo, e);
188 }
189 }
190
191 private void startClient() throws IOException {
192 client = SshClient.setUpDefaultClient();
Sean Condon7347de92017-07-21 12:17:25 +0100193 client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100194 TimeUnit.SECONDS.toMillis(idleTimeout));
Sean Condon7347de92017-07-21 12:17:25 +0100195 client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100196 TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700197 client.start();
198 client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
199 startSession();
200 }
201
202 private void startSession() throws IOException {
203 final ConnectFuture connectFuture;
204 connectFuture = client.connect(deviceInfo.name(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200205 deviceInfo.ip().toString(),
206 deviceInfo.port())
Sean Condon54d82432017-07-26 22:27:25 +0100207 .verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700208 session = connectFuture.getSession();
209 //Using the device ssh key if possible
210 if (deviceInfo.getKey() != null) {
211 ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(deviceInfo.getKey()));
212 byte[] byteKey = new byte[buf.limit()];
213 buf.get(byteKey);
214 PublicKey key;
215 try {
216 key = getPublicKey(byteKey, RSA);
217 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
218 try {
219 key = getPublicKey(byteKey, DSA);
220 } catch (NoSuchAlgorithmException | InvalidKeySpecException e1) {
221 throw new NetconfException("Failed to authenticate session with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200222 deviceInfo + "check key to be the " +
223 "proper DSA or RSA key", e1);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700224 }
225 }
226 //privateKye can set tu null because is not used by the method.
227 session.addPublicKeyIdentity(new KeyPair(key, null));
228 } else {
229 session.addPasswordIdentity(deviceInfo.password());
230 }
Sean Condon54d82432017-07-26 22:27:25 +0100231 session.auth().verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700232 Set<ClientSession.ClientSessionEvent> event = session.waitFor(
233 ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200234 ClientSession.ClientSessionEvent.CLOSED,
235 ClientSession.ClientSessionEvent.AUTHED), 0);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700236
237 if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
238 log.debug("Session closed {} {}", event, session.isClosed());
239 throw new NetconfException("Failed to authenticate session with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200240 deviceInfo + "check the user/pwd or key");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700241 }
242 openChannel();
243 }
244
245 private PublicKey getPublicKey(byte[] keyBytes, String type)
246 throws NoSuchAlgorithmException, InvalidKeySpecException {
247
248 X509EncodedKeySpec spec =
249 new X509EncodedKeySpec(keyBytes);
250 KeyFactory kf = KeyFactory.getInstance(type);
251 return kf.generatePublic(spec);
252 }
253
254 private void openChannel() throws IOException {
255 channel = session.createSubsystemChannel("netconf");
256 OpenFuture channelFuture = channel.open();
Sean Condon54d82432017-07-26 22:27:25 +0100257 if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700258 if (channelFuture.isOpened()) {
259 streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200260 channel.getInvertedErr(), deviceInfo,
261 new NetconfSessionDelegateImpl(), replies);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700262 } else {
263 throw new NetconfException("Failed to open channel with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200264 deviceInfo);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700265 }
266 sendHello();
267 }
268 }
269
270
271 @Beta
272 protected void startSubscriptionStream(String filterSchema) throws NetconfException {
273 boolean openNewSession = false;
274 if (!deviceCapabilities.contains(INTERLEAVE_CAPABILITY_STRING)) {
275 log.info("Device {} doesn't support interleave, creating child session", deviceInfo);
276 openNewSession = true;
277
278 } else if (subscriptionConnected &&
279 notificationFilterSchema != null &&
280 !Objects.equal(filterSchema, notificationFilterSchema)) {
281 // interleave supported and existing filter is NOT "no filtering"
282 // and was requested with different filtering schema
283 log.info("Cannot use existing session for subscription {} ({})",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200284 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700285 openNewSession = true;
286 }
287
288 if (openNewSession) {
289 log.info("Creating notification session to {} with filter {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200290 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700291 NetconfSession child = new NotificationSession(deviceInfo);
292
293 child.addDeviceOutputListener(new NotificationForwarder());
294
295 child.startSubscription(filterSchema);
296 children.add(child);
297 return;
298 }
299
300 // request to start interleaved notification session
301 String reply = sendRequest(createSubscriptionString(filterSchema));
302 if (!checkReply(reply)) {
303 throw new NetconfException("Subscription not successful with device "
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200304 + deviceInfo + " with reply " + reply);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700305 }
306 subscriptionConnected = true;
307 }
308
309 @Override
310 public void startSubscription() throws NetconfException {
311 if (!subscriptionConnected) {
312 startSubscriptionStream(null);
313 }
314 streamHandler.setEnableNotifications(true);
315 }
316
317 @Beta
318 @Override
319 public void startSubscription(String filterSchema) throws NetconfException {
320 if (!subscriptionConnected) {
321 notificationFilterSchema = filterSchema;
322 startSubscriptionStream(filterSchema);
323 }
324 streamHandler.setEnableNotifications(true);
325 }
326
327 @Beta
328 protected String createSubscriptionString(String filterSchema) {
329 StringBuilder subscriptionbuffer = new StringBuilder();
330 subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
331 subscriptionbuffer.append(" <create-subscription\n");
332 subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n");
333 // FIXME Only subtree filtering supported at the moment.
334 if (filterSchema != null) {
335 subscriptionbuffer.append(" ");
336 subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE);
337 subscriptionbuffer.append(filterSchema).append(NEW_LINE);
338 subscriptionbuffer.append(" ");
339 subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
340 }
341 subscriptionbuffer.append(" </create-subscription>\n");
342 subscriptionbuffer.append("</rpc>\n");
343 subscriptionbuffer.append(ENDPATTERN);
344 return subscriptionbuffer.toString();
345 }
346
347 @Override
348 public void endSubscription() throws NetconfException {
349 if (subscriptionConnected) {
350 streamHandler.setEnableNotifications(false);
351 } else {
352 throw new NetconfException("Subscription does not exist.");
353 }
354 }
355
356 private void sendHello() throws NetconfException {
357 serverHelloResponseOld = sendRequest(createHelloString(), true);
358 Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponseOld);
359 while (capabilityMatcher.find()) {
360 deviceCapabilities.add(capabilityMatcher.group(1));
361 }
362 sessionID = String.valueOf(-1);
363 Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponseOld);
364 if (sessionIDMatcher.find()) {
365 sessionID = sessionIDMatcher.group(1);
366 } else {
367 throw new NetconfException("Missing SessionID in server hello " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200368 "reponse.");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700369 }
370
371 }
372
373 private String createHelloString() {
374 StringBuilder hellobuffer = new StringBuilder();
375 hellobuffer.append(XML_HEADER);
376 hellobuffer.append("\n");
377 hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
378 hellobuffer.append(" <capabilities>\n");
379 onosCapabilities.forEach(
380 cap -> hellobuffer.append(" <capability>")
381 .append(cap)
382 .append("</capability>\n"));
383 hellobuffer.append(" </capabilities>\n");
384 hellobuffer.append("</hello>\n");
385 hellobuffer.append(ENDPATTERN);
386 return hellobuffer.toString();
387
388 }
389
390 @Override
391 public void checkAndReestablish() throws NetconfException {
392 try {
393 if (client.isClosed()) {
394 log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId());
395 cleanUp();
396 startConnection();
397 } else if (session.isClosed()) {
398 log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId());
399 cleanUp();
400 startSession();
401 } else if (channel.isClosed()) {
402 log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId());
403 cleanUp();
404 openChannel();
405 }
406 if (subscriptionConnected) {
407 log.debug("Restarting subscription with {}", deviceInfo.getDeviceId());
408 subscriptionConnected = false;
409 startSubscription(notificationFilterSchema);
410 }
Sean Condon7347de92017-07-21 12:17:25 +0100411 } catch (IOException | IllegalStateException e) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700412 log.error("Can't reopen connection for device {}", e.getMessage());
413 throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e);
414 }
415 }
416
417 private void cleanUp() {
418 //makes sure everything is at a clean state.
419 replies.clear();
420 }
421
422 @Override
423 public String requestSync(String request) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700424 String reply = sendRequest(request);
425 checkReply(reply);
426 return reply;
427 }
428
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200429
430 /**
431 * Validate and format netconf message.
432 *
433 * @param message to format
434 * @return formated message
435 */
436 private String formatNetconfMessage(String message) {
437 if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) {
438 message = formatChunkedMessage(message);
439 } else {
440 if (!message.contains(ENDPATTERN)) {
441 message = message + NEW_LINE + ENDPATTERN;
442 }
443 }
444 return message;
445 }
446
447 /**
448 * Validate and format message according to chunked framing mechanism.
449 *
450 * @param message to format
451 * @return formated message
452 */
453 private String formatChunkedMessage(String message) {
454 if (message.endsWith(ENDPATTERN)) {
455 message = message.substring(0, message.length() - ENDPATTERN.length());
456 }
457 if (!message.startsWith(LF + HASH)) {
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700458 message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200459 }
460 return message;
461 }
462
463
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700464 @Override
465 @Deprecated
466 public CompletableFuture<String> request(String request) {
467 return streamHandler.sendMessage(request);
468 }
469
Sean Condon54d82432017-07-26 22:27:25 +0100470 @Override
471 public int timeoutConnectSec() {
472 return connectTimeout;
473 }
474
475 @Override
476 public int timeoutReplySec() {
477 return replyTimeout;
478 }
479
480 @Override
481 public int timeoutIdleSec() {
482 return idleTimeout;
483 }
484
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700485 private CompletableFuture<String> request(String request, int messageId) {
486 return streamHandler.sendMessage(request, messageId);
487 }
488
489 private String sendRequest(String request) throws NetconfException {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200490 request = formatNetconfMessage(request);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700491 return sendRequest(request, false);
492 }
493
494 private String sendRequest(String request, boolean isHello) throws NetconfException {
495 checkAndReestablish();
496 int messageId = -1;
497 if (!isHello) {
498 messageId = messageIdInteger.getAndIncrement();
499 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700500 request = formatXmlHeader(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200501 request = formatRequestMessageId(request, messageId);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700502 CompletableFuture<String> futureReply = request(request, messageId);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700503 String rp;
504 try {
Sean Condon54d82432017-07-26 22:27:25 +0100505 log.debug("Sending request to NETCONF with timeout {} for {}",
506 replyTimeout, deviceInfo.name());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700507 rp = futureReply.get(replyTimeout, TimeUnit.SECONDS);
Sean Condon7347de92017-07-21 12:17:25 +0100508 replies.remove(messageId); // Why here???
509 } catch (InterruptedException e) {
510 Thread.currentThread().interrupt();
511 throw new NetconfException("Interrupted waiting for reply for request" + request, e);
512 } catch (TimeoutException e) {
Sean Condon54d82432017-07-26 22:27:25 +0100513 throw new NetconfException("Timed out waiting for reply for request " +
514 request + " after " + replyTimeout + " sec.", e);
Sean Condon7347de92017-07-21 12:17:25 +0100515 } catch (ExecutionException e) {
516 log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e);
517 try {
518 session.close();
519 channel.close(); //Closes the socket which should interrupt NetconfStreamThread
520 client.close();
521 } catch (IOException ioe) {
522 log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe);
523 }
524 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
525 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
526 null, "Closed due to unexpected error " + e.getCause(),
527 Optional.of(-1), deviceInfo);
528 publishEvent(event);
529 errorReplies.clear(); // move to cleanUp()?
530 cleanUp();
531
532 throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo +
533 " for request " + request, e);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700534 }
535 log.debug("Result {} from request {} to device {}", rp, request, deviceInfo);
536 return rp.trim();
537 }
538
539 private String formatRequestMessageId(String request, int messageId) {
540 if (request.contains(MESSAGE_ID_STRING)) {
541 //FIXME if application provides his own counting of messages this fails that count
542 request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200543 MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\"");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700544 } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) {
545 //FIXME find out a better way to enforce the presence of message-id
546 request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\""
547 + messageId + "\"" + ">");
548 }
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200549 request = updateRequestLenght(request);
550 return request;
551 }
552
553 private String updateRequestLenght(String request) {
554 if (request.contains(LF + HASH + HASH + LF)) {
555 int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]);
556 String rpcWithEnding = request.substring(request.indexOf('<'));
557 String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0];
558 int newLen = 0;
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700559 newLen = firstBlock.getBytes(UTF_8).length;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200560 if (oldLen != newLen) {
561 return LF + HASH + newLen + LF + rpcWithEnding;
562 }
563 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700564 return request;
565 }
566
567 private String formatXmlHeader(String request) {
568 if (!request.contains(XML_HEADER)) {
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700569 //FIXME if application provides his own XML header of different type there is a clash
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200570 if (request.startsWith(LF + HASH)) {
571 request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length());
572 } else {
573 request = XML_HEADER + "\n" + request;
574 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700575 }
576 return request;
577 }
578
579 @Override
580 public String doWrappedRpc(String request) throws NetconfException {
581 StringBuilder rpc = new StringBuilder(XML_HEADER);
582 rpc.append(RPC_OPEN);
583 rpc.append(MESSAGE_ID_STRING);
584 rpc.append(EQUAL);
585 rpc.append("\"");
586 rpc.append(messageIdInteger.get());
587 rpc.append("\" ");
588 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
589 rpc.append(request);
590 rpc.append(RPC_CLOSE).append(NEW_LINE);
591 rpc.append(ENDPATTERN);
592 String reply = sendRequest(rpc.toString());
593 checkReply(reply);
594 return reply;
595 }
596
597 @Override
598 public String get(String request) throws NetconfException {
599 return requestSync(request);
600 }
601
602 @Override
603 public String get(String filterSchema, String withDefaultsMode) throws NetconfException {
604 StringBuilder rpc = new StringBuilder(XML_HEADER);
605 rpc.append(RPC_OPEN);
606 rpc.append(MESSAGE_ID_STRING);
607 rpc.append(EQUAL);
608 rpc.append("\"");
609 rpc.append(messageIdInteger.get());
610 rpc.append("\" ");
611 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
612 rpc.append(GET_OPEN).append(NEW_LINE);
613 if (filterSchema != null) {
614 rpc.append(SUBTREE_FILTER_OPEN).append(NEW_LINE);
615 rpc.append(filterSchema).append(NEW_LINE);
616 rpc.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
617 }
618 if (withDefaultsMode != null) {
619 rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">");
620 rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE);
621 }
622 rpc.append(GET_CLOSE).append(NEW_LINE);
623 rpc.append(RPC_CLOSE).append(NEW_LINE);
624 rpc.append(ENDPATTERN);
625 String reply = sendRequest(rpc.toString());
626 checkReply(reply);
627 return reply;
628 }
629
630 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700631 public String getConfig(DatastoreId netconfTargetConfig) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700632 return getConfig(netconfTargetConfig, null);
633 }
634
635 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700636 public String getConfig(DatastoreId netconfTargetConfig,
637 String configurationSchema) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700638 StringBuilder rpc = new StringBuilder(XML_HEADER);
639 rpc.append("<rpc ");
640 rpc.append(MESSAGE_ID_STRING);
641 rpc.append(EQUAL);
642 rpc.append("\"");
643 rpc.append(messageIdInteger.get());
644 rpc.append("\" ");
645 rpc.append("xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
646 rpc.append("<get-config>\n");
647 rpc.append("<source>\n");
648 rpc.append("<").append(netconfTargetConfig).append("/>");
649 rpc.append("</source>");
650 if (configurationSchema != null) {
651 rpc.append("<filter type=\"subtree\">\n");
652 rpc.append(configurationSchema).append("\n");
653 rpc.append("</filter>\n");
654 }
655 rpc.append("</get-config>\n");
656 rpc.append("</rpc>\n");
657 rpc.append(ENDPATTERN);
658 String reply = sendRequest(rpc.toString());
659 return checkReply(reply) ? reply : "ERROR " + reply;
660 }
661
662 @Override
663 public boolean editConfig(String newConfiguration) throws NetconfException {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200664 if (!newConfiguration.endsWith(ENDPATTERN)) {
665 newConfiguration = newConfiguration + ENDPATTERN;
666 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700667 return checkReply(sendRequest(newConfiguration));
668 }
669
670 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700671 public boolean editConfig(DatastoreId netconfTargetConfig,
672 String mode,
673 String newConfiguration)
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700674 throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700675
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700676 newConfiguration = newConfiguration.trim();
677 StringBuilder rpc = new StringBuilder(XML_HEADER);
678 rpc.append(RPC_OPEN);
679 rpc.append(MESSAGE_ID_STRING);
680 rpc.append(EQUAL);
681 rpc.append("\"");
682 rpc.append(messageIdInteger.get());
683 rpc.append("\" ");
684 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
685 rpc.append(EDIT_CONFIG_OPEN).append("\n");
686 rpc.append(TARGET_OPEN);
687 rpc.append("<").append(netconfTargetConfig).append("/>");
688 rpc.append(TARGET_CLOSE).append("\n");
689 if (mode != null) {
690 rpc.append(DEFAULT_OPERATION_OPEN);
691 rpc.append(mode);
692 rpc.append(DEFAULT_OPERATION_CLOSE).append("\n");
693 }
694 rpc.append(CONFIG_OPEN).append("\n");
695 rpc.append(newConfiguration);
696 rpc.append(CONFIG_CLOSE).append("\n");
697 rpc.append(EDIT_CONFIG_CLOSE).append("\n");
698 rpc.append(RPC_CLOSE);
699 rpc.append(ENDPATTERN);
700 log.debug(rpc.toString());
701 String reply = sendRequest(rpc.toString());
702 return checkReply(reply);
703 }
704
705 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700706 public boolean copyConfig(DatastoreId destination,
707 DatastoreId source)
708 throws NetconfException {
709 return bareCopyConfig(destination.asXml(), source.asXml());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700710 }
711
712 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700713 public boolean copyConfig(DatastoreId netconfTargetConfig,
714 String newConfiguration)
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700715 throws NetconfException {
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700716 return bareCopyConfig(netconfTargetConfig.asXml(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200717 normalizeCopyConfigParam(newConfiguration));
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700718 }
719
720 @Override
721 public boolean copyConfig(String netconfTargetConfig,
722 String newConfiguration) throws NetconfException {
723 return bareCopyConfig(normalizeCopyConfigParam(netconfTargetConfig),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200724 normalizeCopyConfigParam(newConfiguration));
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700725 }
726
727 /**
728 * Normalize String parameter passed to copy-config API.
729 * <p>
730 * Provided for backward compatibility purpose
731 *
732 * @param input passed to copyConfig API
733 * @return XML likely to be suitable for copy-config source or target
734 */
735 private static CharSequence normalizeCopyConfigParam(String input) {
736 input = input.trim();
737 if (input.startsWith("<url")) {
738 return input;
739 } else if (!input.startsWith("<")) {
740 // assume it is a datastore name
741 return DatastoreId.datastore(input).asXml();
742 } else if (!input.startsWith("<config>")) {
743 return "<config>" + input + "</config>";
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700744 }
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700745 return input;
746 }
747
748 private boolean bareCopyConfig(CharSequence target,
749 CharSequence source)
750 throws NetconfException {
751
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700752 StringBuilder rpc = new StringBuilder(XML_HEADER);
753 rpc.append(RPC_OPEN);
754 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
755 rpc.append("<copy-config>");
756 rpc.append("<target>");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700757 rpc.append(target);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700758 rpc.append("</target>");
759 rpc.append("<source>");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700760 rpc.append(source);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700761 rpc.append("</source>");
762 rpc.append("</copy-config>");
763 rpc.append("</rpc>");
764 rpc.append(ENDPATTERN);
765 return checkReply(sendRequest(rpc.toString()));
766 }
767
768 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700769 public boolean deleteConfig(DatastoreId netconfTargetConfig) throws NetconfException {
770 if (netconfTargetConfig.equals(DatastoreId.RUNNING)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700771 log.warn("Target configuration for delete operation can't be \"running\"",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200772 netconfTargetConfig);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700773 return false;
774 }
775 StringBuilder rpc = new StringBuilder(XML_HEADER);
776 rpc.append("<rpc>");
777 rpc.append("<delete-config>");
778 rpc.append("<target>");
779 rpc.append("<").append(netconfTargetConfig).append("/>");
780 rpc.append("</target>");
781 rpc.append("</delete-config>");
782 rpc.append("</rpc>");
783 rpc.append(ENDPATTERN);
784 return checkReply(sendRequest(rpc.toString()));
785 }
786
787 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700788 public boolean lock(DatastoreId configType) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700789 StringBuilder rpc = new StringBuilder(XML_HEADER);
790 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
791 rpc.append("<lock>");
792 rpc.append("<target>");
793 rpc.append("<");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700794 rpc.append(configType.id());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700795 rpc.append("/>");
796 rpc.append("</target>");
797 rpc.append("</lock>");
798 rpc.append("</rpc>");
799 rpc.append(ENDPATTERN);
800 String lockReply = sendRequest(rpc.toString());
801 return checkReply(lockReply);
802 }
803
804 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700805 public boolean unlock(DatastoreId configType) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700806 StringBuilder rpc = new StringBuilder(XML_HEADER);
807 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
808 rpc.append("<unlock>");
809 rpc.append("<target>");
810 rpc.append("<");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700811 rpc.append(configType.id());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700812 rpc.append("/>");
813 rpc.append("</target>");
814 rpc.append("</unlock>");
815 rpc.append("</rpc>");
816 rpc.append(ENDPATTERN);
817 String unlockReply = sendRequest(rpc.toString());
818 return checkReply(unlockReply);
819 }
820
821 @Override
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700822 public boolean close() throws NetconfException {
823 return close(false);
824 }
825
826 private boolean close(boolean force) throws NetconfException {
827 StringBuilder rpc = new StringBuilder();
828 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">");
829 if (force) {
830 rpc.append("<kill-session/>");
831 } else {
832 rpc.append("<close-session/>");
833 }
834 rpc.append("</rpc>");
835 rpc.append(ENDPATTERN);
836 return checkReply(sendRequest(rpc.toString())) || close(true);
837 }
838
839 @Override
840 public String getSessionId() {
841 return sessionID;
842 }
843
844 @Override
845 public Set<String> getDeviceCapabilitiesSet() {
846 return Collections.unmodifiableSet(deviceCapabilities);
847 }
848
849 @Deprecated
850 @Override
851 public String getServerCapabilities() {
852 return serverHelloResponseOld;
853 }
854
855 @Deprecated
856 @Override
857 public void setDeviceCapabilities(List<String> capabilities) {
858 onosCapabilities = capabilities;
859 }
860
861 @Override
862 public void setOnosCapabilities(Iterable<String> capabilities) {
863 onosCapabilities = capabilities;
864 }
865
866
867 @Override
868 public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
869 streamHandler.addDeviceEventListener(listener);
870 primaryListeners.add(listener);
871 }
872
873 @Override
874 public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
875 primaryListeners.remove(listener);
876 streamHandler.removeDeviceEventListener(listener);
877 }
878
879 private boolean checkReply(String reply) throws NetconfException {
880 if (reply != null) {
881 if (!reply.contains("<rpc-error>")) {
882 log.debug("Device {} sent reply {}", deviceInfo, reply);
883 return true;
884 } else if (reply.contains("<ok/>")
885 || (reply.contains("<rpc-error>")
886 && reply.contains("warning"))) {
887 log.debug("Device {} sent reply {}", deviceInfo, reply);
888 return true;
889 }
890 }
891 log.warn("Device {} has error in reply {}", deviceInfo, reply);
892 return false;
893 }
894
Sean Condon7347de92017-07-21 12:17:25 +0100895 protected void publishEvent(NetconfDeviceOutputEvent event) {
896 primaryListeners.forEach(lsnr -> {
897 if (lsnr.isRelevant(event)) {
898 lsnr.event(event);
899 }
900 });
901 }
902
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700903 static class NotificationSession extends NetconfSessionMinaImpl {
904
905 private String notificationFilter;
906
907 NotificationSession(NetconfDeviceInfo deviceInfo)
908 throws NetconfException {
909 super(deviceInfo);
910 }
911
912 @Override
913 protected void startSubscriptionStream(String filterSchema)
914 throws NetconfException {
915
916 notificationFilter = filterSchema;
917 requestSync(createSubscriptionString(filterSchema));
918 }
919
920 @Override
921 public String toString() {
922 return MoreObjects.toStringHelper(getClass())
923 .add("deviceInfo", deviceInfo)
924 .add("sessionID", getSessionId())
925 .add("notificationFilter", notificationFilter)
926 .toString();
927 }
928 }
929
930 /**
931 * Listener attached to child session for notification streaming.
932 * <p>
933 * Forwards all notification event from child session to primary session
934 * listeners.
935 */
936 private final class NotificationForwarder
937 implements NetconfDeviceOutputEventListener {
938
939 @Override
940 public boolean isRelevant(NetconfDeviceOutputEvent event) {
941 return event.type() == Type.DEVICE_NOTIFICATION;
942 }
943
944 @Override
945 public void event(NetconfDeviceOutputEvent event) {
Sean Condon7347de92017-07-21 12:17:25 +0100946 publishEvent(event);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700947 }
948 }
949
950 public class NetconfSessionDelegateImpl implements NetconfSessionDelegate {
951
952 @Override
953 public void notify(NetconfDeviceOutputEvent event) {
954 Optional<Integer> messageId = event.getMessageID();
955 log.debug("messageID {}, waiting replies messageIDs {}", messageId,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200956 replies.keySet());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700957 if (!messageId.isPresent()) {
958 errorReplies.add(event.getMessagePayload());
959 log.error("Device {} sent error reply {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200960 event.getDeviceInfo(), event.getMessagePayload());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700961 return;
962 }
963 CompletableFuture<String> completedReply =
Sean Condon7347de92017-07-21 12:17:25 +0100964 replies.get(messageId.get()); // remove(..)?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700965 if (completedReply != null) {
966 completedReply.complete(event.getMessagePayload());
967 }
968 }
969 }
970
971 public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory {
972
973 @Override
974 public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException {
975 return new NetconfSessionMinaImpl(netconfDeviceInfo);
976 }
977 }
Sean Condon54d82432017-07-26 22:27:25 +0100978}