blob: b9875306b1799ccbe0d6c2881f1164d29589e7b4 [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;
Holger Schulz092cbbf2017-08-31 17:52:30 +020031import org.bouncycastle.jce.provider.BouncyCastleProvider;
32import org.bouncycastle.openssl.PEMParser;
33import org.bouncycastle.openssl.PEMKeyPair;
34import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070035import org.onlab.util.SharedExecutors;
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -070036import org.onosproject.netconf.DatastoreId;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070037import org.onosproject.netconf.NetconfDeviceInfo;
38import org.onosproject.netconf.NetconfDeviceOutputEvent;
39import org.onosproject.netconf.NetconfDeviceOutputEvent.Type;
40import org.onosproject.netconf.NetconfDeviceOutputEventListener;
41import org.onosproject.netconf.NetconfException;
42import org.onosproject.netconf.NetconfSession;
43import org.onosproject.netconf.NetconfSessionFactory;
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070044import org.onosproject.netconf.NetconfTransportException;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070045import org.slf4j.Logger;
Yuta HIGUCHI15677982017-08-16 15:50:29 -070046import static java.nio.charset.StandardCharsets.UTF_8;
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070047import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI15677982017-08-16 15:50:29 -070048
Holger Schulz092cbbf2017-08-31 17:52:30 +020049import java.io.CharArrayReader;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070050import java.io.IOException;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070051import java.security.KeyFactory;
52import java.security.KeyPair;
53import java.security.NoSuchAlgorithmException;
54import java.security.PublicKey;
55import java.security.spec.InvalidKeySpecException;
56import java.security.spec.X509EncodedKeySpec;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020057import java.util.LinkedHashSet;
58import java.util.Map;
59import java.util.Set;
60import java.util.List;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070061import java.util.Collection;
62import java.util.Collections;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070063import java.util.Optional;
Kamil Stasiak9f59f442017-05-02 11:02:24 +020064import java.util.ArrayList;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070065import java.util.concurrent.CompletableFuture;
66import java.util.concurrent.ConcurrentHashMap;
67import java.util.concurrent.CopyOnWriteArrayList;
68import java.util.concurrent.ExecutionException;
69import java.util.concurrent.TimeUnit;
70import java.util.concurrent.TimeoutException;
71import java.util.concurrent.atomic.AtomicInteger;
72import java.util.regex.Matcher;
73import java.util.regex.Pattern;
74
75/**
76 * Implementation of a NETCONF session to talk to a device.
77 */
78public class NetconfSessionMinaImpl implements NetconfSession {
79
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070080 private static final Logger log = getLogger(NetconfSessionMinaImpl.class);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070081
Yuta HIGUCHI371667d2017-09-05 17:30:51 -070082 /**
83 * NC 1.0, RFC4742 EOM sequence.
84 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070085 private static final String ENDPATTERN = "]]>]]>";
86 private static final String MESSAGE_ID_STRING = "message-id";
87 private static final String HELLO = "<hello";
88 private static final String NEW_LINE = "\n";
89 private static final String END_OF_RPC_OPEN_TAG = "\">";
90 private static final String EQUAL = "=";
91 private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"";
92 private static final String RPC_OPEN = "<rpc ";
93 private static final String RPC_CLOSE = "</rpc>";
94 private static final String GET_OPEN = "<get>";
95 private static final String GET_CLOSE = "</get>";
96 private static final String WITH_DEFAULT_OPEN = "<with-defaults ";
97 private static final String WITH_DEFAULT_CLOSE = "</with-defaults>";
98 private static final String DEFAULT_OPERATION_OPEN = "<default-operation>";
99 private static final String DEFAULT_OPERATION_CLOSE = "</default-operation>";
100 private static final String SUBTREE_FILTER_OPEN = "<filter type=\"subtree\">";
101 private static final String SUBTREE_FILTER_CLOSE = "</filter>";
102 private static final String EDIT_CONFIG_OPEN = "<edit-config>";
103 private static final String EDIT_CONFIG_CLOSE = "</edit-config>";
104 private static final String TARGET_OPEN = "<target>";
105 private static final String TARGET_CLOSE = "</target>";
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700106 // FIXME hard coded namespace nc
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700107 private static final String CONFIG_OPEN = "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
108 private static final String CONFIG_CLOSE = "</config>";
109 private static final String XML_HEADER =
110 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
111 private static final String NETCONF_BASE_NAMESPACE =
112 "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"";
113 private static final String NETCONF_WITH_DEFAULTS_NAMESPACE =
114 "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\"";
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700115 // FIXME hard coded namespace base10
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700116 private static final String SUBSCRIPTION_SUBTREE_FILTER_OPEN =
117 "<filter xmlns:base10=\"urn:ietf:params:xml:ns:netconf:base:1.0\" base10:type=\"subtree\">";
118
119 private static final String INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0";
120
121 private static final String CAPABILITY_REGEX = "<capability>\\s*(.*?)\\s*</capability>";
122 private static final Pattern CAPABILITY_REGEX_PATTERN = Pattern.compile(CAPABILITY_REGEX);
123
124 private static final String SESSION_ID_REGEX = "<session-id>\\s*(.*?)\\s*</session-id>";
125 private static final Pattern SESSION_ID_REGEX_PATTERN = Pattern.compile(SESSION_ID_REGEX);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200126 private static final String HASH = "#";
127 private static final String LF = "\n";
128 private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n";
129 private static final String NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0";
130 private static final String NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1";
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700131
132 private String sessionID;
133 private final AtomicInteger messageIdInteger = new AtomicInteger(1);
134 protected final NetconfDeviceInfo deviceInfo;
135 private Iterable<String> onosCapabilities =
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200136 ImmutableList.of(NETCONF_10_CAPABILITY, NETCONF_11_CAPABILITY);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700137
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700138 private final Set<String> deviceCapabilities = new LinkedHashSet<>();
139 private NetconfStreamHandler streamHandler;
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700140 // FIXME ONOS-7019 key type should be revised to a String, see RFC6241
141 /**
142 * Message-ID and corresponding Future waiting for response.
143 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700144 private Map<Integer, CompletableFuture<String>> replies;
Sean Condon7347de92017-07-21 12:17:25 +0100145 private List<String> errorReplies; // Not sure why we need this?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700146 private boolean subscriptionConnected = false;
147 private String notificationFilterSchema = null;
148
149 private final Collection<NetconfDeviceOutputEventListener> primaryListeners =
150 new CopyOnWriteArrayList<>();
151 private final Collection<NetconfSession> children =
152 new CopyOnWriteArrayList<>();
153
Sean Condon54d82432017-07-26 22:27:25 +0100154 private int connectTimeout;
155 private int replyTimeout;
156 private int idleTimeout;
157
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700158
159 private ClientChannel channel = null;
160 private ClientSession session = null;
161 private SshClient client = null;
162
163
164 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
165 this.deviceInfo = deviceInfo;
166 replies = new ConcurrentHashMap<>();
167 errorReplies = new ArrayList<>();
Sean Condon54d82432017-07-26 22:27:25 +0100168
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700169 // FIXME should not immediately start session on construction
170 // setOnosCapabilities() is useless due to this behavior
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700171 startConnection();
172 }
173
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200174 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo, List<String> capabilities) throws NetconfException {
175 this.deviceInfo = deviceInfo;
176 replies = new ConcurrentHashMap<>();
177 errorReplies = new ArrayList<>();
178 setOnosCapabilities(capabilities);
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700179 // FIXME should not immediately start session on construction
180 // setOnosCapabilities() is useless due to this behavior
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200181 startConnection();
182 }
183
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700184 private void startConnection() throws NetconfException {
Sean Condon54d82432017-07-26 22:27:25 +0100185 connectTimeout = deviceInfo.getConnectTimeoutSec().orElse(
186 NetconfControllerImpl.netconfConnectTimeout);
187 replyTimeout = deviceInfo.getReplyTimeoutSec().orElse(
188 NetconfControllerImpl.netconfReplyTimeout);
189 idleTimeout = deviceInfo.getIdleTimeoutSec().orElse(
190 NetconfControllerImpl.netconfIdleTimeout);
191 log.info("Connecting to {} with timeouts C:{}, R:{}, I:{}", deviceInfo,
192 connectTimeout, replyTimeout, idleTimeout);
193
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700194 try {
195 startClient();
196 } catch (IOException e) {
197 throw new NetconfException("Failed to establish SSH with device " + deviceInfo, e);
198 }
199 }
200
201 private void startClient() throws IOException {
202 client = SshClient.setUpDefaultClient();
Sean Condon7347de92017-07-21 12:17:25 +0100203 client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100204 TimeUnit.SECONDS.toMillis(idleTimeout));
Sean Condon7347de92017-07-21 12:17:25 +0100205 client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100206 TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700207 client.start();
208 client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
209 startSession();
210 }
211
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700212 // FIXME blocking
213 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700214 private void startSession() throws IOException {
215 final ConnectFuture connectFuture;
216 connectFuture = client.connect(deviceInfo.name(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200217 deviceInfo.ip().toString(),
218 deviceInfo.port())
Sean Condon54d82432017-07-26 22:27:25 +0100219 .verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700220 session = connectFuture.getSession();
221 //Using the device ssh key if possible
222 if (deviceInfo.getKey() != null) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700223 try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
224 JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
225 try {
226 KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
227 session.addPublicKeyIdentity(kp);
228 } catch (IOException e) {
229 throw new NetconfException("Failed to authenticate session with device " +
230 deviceInfo + "check key to be a valid key", e);
231 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700232 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700233 } else {
234 session.addPasswordIdentity(deviceInfo.password());
235 }
Sean Condon54d82432017-07-26 22:27:25 +0100236 session.auth().verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700237 Set<ClientSession.ClientSessionEvent> event = session.waitFor(
238 ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200239 ClientSession.ClientSessionEvent.CLOSED,
240 ClientSession.ClientSessionEvent.AUTHED), 0);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700241
242 if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
243 log.debug("Session closed {} {}", event, session.isClosed());
244 throw new NetconfException("Failed to authenticate session with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200245 deviceInfo + "check the user/pwd or key");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700246 }
247 openChannel();
248 }
249
250 private PublicKey getPublicKey(byte[] keyBytes, String type)
251 throws NoSuchAlgorithmException, InvalidKeySpecException {
252
253 X509EncodedKeySpec spec =
254 new X509EncodedKeySpec(keyBytes);
255 KeyFactory kf = KeyFactory.getInstance(type);
256 return kf.generatePublic(spec);
257 }
258
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700259 // FIXME blocking
260 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700261 private void openChannel() throws IOException {
262 channel = session.createSubsystemChannel("netconf");
263 OpenFuture channelFuture = channel.open();
Sean Condon54d82432017-07-26 22:27:25 +0100264 if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700265 if (channelFuture.isOpened()) {
266 streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200267 channel.getInvertedErr(), deviceInfo,
268 new NetconfSessionDelegateImpl(), replies);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700269 } else {
270 throw new NetconfException("Failed to open channel with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200271 deviceInfo);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700272 }
273 sendHello();
274 }
275 }
276
277
278 @Beta
279 protected void startSubscriptionStream(String filterSchema) throws NetconfException {
280 boolean openNewSession = false;
281 if (!deviceCapabilities.contains(INTERLEAVE_CAPABILITY_STRING)) {
282 log.info("Device {} doesn't support interleave, creating child session", deviceInfo);
283 openNewSession = true;
284
285 } else if (subscriptionConnected &&
286 notificationFilterSchema != null &&
287 !Objects.equal(filterSchema, notificationFilterSchema)) {
288 // interleave supported and existing filter is NOT "no filtering"
289 // and was requested with different filtering schema
290 log.info("Cannot use existing session for subscription {} ({})",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200291 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700292 openNewSession = true;
293 }
294
295 if (openNewSession) {
296 log.info("Creating notification session to {} with filter {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200297 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700298 NetconfSession child = new NotificationSession(deviceInfo);
299
300 child.addDeviceOutputListener(new NotificationForwarder());
301
302 child.startSubscription(filterSchema);
303 children.add(child);
304 return;
305 }
306
307 // request to start interleaved notification session
308 String reply = sendRequest(createSubscriptionString(filterSchema));
309 if (!checkReply(reply)) {
310 throw new NetconfException("Subscription not successful with device "
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200311 + deviceInfo + " with reply " + reply);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700312 }
313 subscriptionConnected = true;
314 }
315
316 @Override
317 public void startSubscription() throws NetconfException {
318 if (!subscriptionConnected) {
319 startSubscriptionStream(null);
320 }
321 streamHandler.setEnableNotifications(true);
322 }
323
324 @Beta
325 @Override
326 public void startSubscription(String filterSchema) throws NetconfException {
327 if (!subscriptionConnected) {
328 notificationFilterSchema = filterSchema;
329 startSubscriptionStream(filterSchema);
330 }
331 streamHandler.setEnableNotifications(true);
332 }
333
334 @Beta
335 protected String createSubscriptionString(String filterSchema) {
336 StringBuilder subscriptionbuffer = new StringBuilder();
337 subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
338 subscriptionbuffer.append(" <create-subscription\n");
339 subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n");
340 // FIXME Only subtree filtering supported at the moment.
341 if (filterSchema != null) {
342 subscriptionbuffer.append(" ");
343 subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE);
344 subscriptionbuffer.append(filterSchema).append(NEW_LINE);
345 subscriptionbuffer.append(" ");
346 subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
347 }
348 subscriptionbuffer.append(" </create-subscription>\n");
349 subscriptionbuffer.append("</rpc>\n");
350 subscriptionbuffer.append(ENDPATTERN);
351 return subscriptionbuffer.toString();
352 }
353
354 @Override
355 public void endSubscription() throws NetconfException {
356 if (subscriptionConnected) {
357 streamHandler.setEnableNotifications(false);
358 } else {
359 throw new NetconfException("Subscription does not exist.");
360 }
361 }
362
363 private void sendHello() throws NetconfException {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700364 String serverHelloResponse = sendRequest(createHelloString(), true);
365 Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700366 while (capabilityMatcher.find()) {
367 deviceCapabilities.add(capabilityMatcher.group(1));
368 }
369 sessionID = String.valueOf(-1);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700370 Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700371 if (sessionIDMatcher.find()) {
372 sessionID = sessionIDMatcher.group(1);
373 } else {
374 throw new NetconfException("Missing SessionID in server hello " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200375 "reponse.");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700376 }
377
378 }
379
380 private String createHelloString() {
381 StringBuilder hellobuffer = new StringBuilder();
382 hellobuffer.append(XML_HEADER);
383 hellobuffer.append("\n");
384 hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
385 hellobuffer.append(" <capabilities>\n");
386 onosCapabilities.forEach(
387 cap -> hellobuffer.append(" <capability>")
388 .append(cap)
389 .append("</capability>\n"));
390 hellobuffer.append(" </capabilities>\n");
391 hellobuffer.append("</hello>\n");
392 hellobuffer.append(ENDPATTERN);
393 return hellobuffer.toString();
394
395 }
396
397 @Override
398 public void checkAndReestablish() throws NetconfException {
399 try {
400 if (client.isClosed()) {
401 log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId());
402 cleanUp();
403 startConnection();
404 } else if (session.isClosed()) {
405 log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId());
406 cleanUp();
407 startSession();
408 } else if (channel.isClosed()) {
409 log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId());
410 cleanUp();
411 openChannel();
Andrea Campanella856f3132017-10-23 15:46:36 +0200412 } else {
413 return;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700414 }
415 if (subscriptionConnected) {
416 log.debug("Restarting subscription with {}", deviceInfo.getDeviceId());
417 subscriptionConnected = false;
418 startSubscription(notificationFilterSchema);
419 }
Sean Condon7347de92017-07-21 12:17:25 +0100420 } catch (IOException | IllegalStateException e) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700421 log.error("Can't reopen connection for device {}", e.getMessage());
422 throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e);
423 }
424 }
425
426 private void cleanUp() {
427 //makes sure everything is at a clean state.
428 replies.clear();
429 }
430
431 @Override
432 public String requestSync(String request) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700433 String reply = sendRequest(request);
434 checkReply(reply);
435 return reply;
436 }
437
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200438
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700439 // FIXME rename to align with what it actually do
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200440 /**
441 * Validate and format netconf message.
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700442 * - NC1.0 if no EOM sequence present on {@code message}, append.
443 * - NC1.1 chunk-encode given message unless it already is chunk encoded
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200444 *
445 * @param message to format
446 * @return formated message
447 */
448 private String formatNetconfMessage(String message) {
449 if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) {
450 message = formatChunkedMessage(message);
451 } else {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700452 if (!message.endsWith(ENDPATTERN)) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200453 message = message + NEW_LINE + ENDPATTERN;
454 }
455 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700456 return message;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200457 }
458
459 /**
460 * Validate and format message according to chunked framing mechanism.
461 *
462 * @param message to format
463 * @return formated message
464 */
465 private String formatChunkedMessage(String message) {
466 if (message.endsWith(ENDPATTERN)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700467 // message given had Netconf 1.0 EOM pattern -> remove
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200468 message = message.substring(0, message.length() - ENDPATTERN.length());
469 }
470 if (!message.startsWith(LF + HASH)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700471 // chunk encode message
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700472 message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200473 }
474 return message;
475 }
476
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700477 @Override
478 @Deprecated
479 public CompletableFuture<String> request(String request) {
480 return streamHandler.sendMessage(request);
481 }
482
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700483 /**
484 * {@inheritDoc}
485 * <p>
486 * FIXME Note: as of 1.12.0
487 * {@code request} must not include message-id, this method will assign
488 * and insert message-id on it's own.
489 * Will require ONOS-7019 to remove this limitation.
490 */
491 @Override
492 public CompletableFuture<String> rpc(String request) {
493
494 String rpc = request;
495 // - assign message-id
496 int msgId = messageIdInteger.incrementAndGet();
497 // - re-write request to insert message-id
498 // FIXME avoid using formatRequestMessageId
499 rpc = formatRequestMessageId(rpc, msgId);
500 // - ensure it contains XML header
501 rpc = formatXmlHeader(rpc);
502 // - use chunked framing if talking to NC 1.1 device
503 // FIXME avoid using formatNetconfMessage
504 rpc = formatNetconfMessage(rpc);
505
506 // TODO session liveness check & recovery
507
508 log.debug("Sending {} to {}", rpc, this.deviceInfo.getDeviceId());
509 return streamHandler.sendMessage(rpc, msgId)
510 .handleAsync((reply, t) -> {
511 if (t != null) {
512 // secure transport-layer error
513 // cannot use NetconfException, which is
514 // checked Exception.
515 throw new NetconfTransportException(t);
516 } else {
517 // FIXME avoid using checkReply, error handling is weird
518 checkReply(reply);
519 return reply;
520 }
521 }, SharedExecutors.getPoolThreadExecutor());
522 }
523
Sean Condon54d82432017-07-26 22:27:25 +0100524 @Override
525 public int timeoutConnectSec() {
526 return connectTimeout;
527 }
528
529 @Override
530 public int timeoutReplySec() {
531 return replyTimeout;
532 }
533
534 @Override
535 public int timeoutIdleSec() {
536 return idleTimeout;
537 }
538
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700539 private CompletableFuture<String> request(String request, int messageId) {
540 return streamHandler.sendMessage(request, messageId);
541 }
542
543 private String sendRequest(String request) throws NetconfException {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700544 // FIXME probably chunk-encoding too early
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200545 request = formatNetconfMessage(request);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700546 return sendRequest(request, false);
547 }
548
549 private String sendRequest(String request, boolean isHello) throws NetconfException {
550 checkAndReestablish();
551 int messageId = -1;
552 if (!isHello) {
553 messageId = messageIdInteger.getAndIncrement();
554 }
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700555 // FIXME potentially re-writing chunked encoded String?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700556 request = formatXmlHeader(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200557 request = formatRequestMessageId(request, messageId);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700558 log.debug("Sending request to NETCONF with timeout {} for {}",
559 replyTimeout, deviceInfo.name());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700560 CompletableFuture<String> futureReply = request(request, messageId);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700561 String rp;
562 try {
563 rp = futureReply.get(replyTimeout, TimeUnit.SECONDS);
Sean Condon7347de92017-07-21 12:17:25 +0100564 replies.remove(messageId); // Why here???
565 } catch (InterruptedException e) {
566 Thread.currentThread().interrupt();
567 throw new NetconfException("Interrupted waiting for reply for request" + request, e);
568 } catch (TimeoutException e) {
Sean Condon54d82432017-07-26 22:27:25 +0100569 throw new NetconfException("Timed out waiting for reply for request " +
570 request + " after " + replyTimeout + " sec.", e);
Sean Condon7347de92017-07-21 12:17:25 +0100571 } catch (ExecutionException e) {
572 log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e);
573 try {
574 session.close();
575 channel.close(); //Closes the socket which should interrupt NetconfStreamThread
576 client.close();
577 } catch (IOException ioe) {
578 log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe);
579 }
580 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
581 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
582 null, "Closed due to unexpected error " + e.getCause(),
583 Optional.of(-1), deviceInfo);
584 publishEvent(event);
585 errorReplies.clear(); // move to cleanUp()?
586 cleanUp();
587
588 throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo +
589 " for request " + request, e);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700590 }
591 log.debug("Result {} from request {} to device {}", rp, request, deviceInfo);
592 return rp.trim();
593 }
594
595 private String formatRequestMessageId(String request, int messageId) {
596 if (request.contains(MESSAGE_ID_STRING)) {
597 //FIXME if application provides his own counting of messages this fails that count
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700598 // FIXME assumes message-id is integer. RFC6241 allows anything as long as it is allowed in XML
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700599 request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200600 MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\"");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700601 } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) {
602 //FIXME find out a better way to enforce the presence of message-id
603 request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\""
604 + messageId + "\"" + ">");
605 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700606 request = updateRequestLength(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200607 return request;
608 }
609
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700610 private String updateRequestLength(String request) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200611 if (request.contains(LF + HASH + HASH + LF)) {
612 int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]);
613 String rpcWithEnding = request.substring(request.indexOf('<'));
614 String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0];
615 int newLen = 0;
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700616 newLen = firstBlock.getBytes(UTF_8).length;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200617 if (oldLen != newLen) {
618 return LF + HASH + newLen + LF + rpcWithEnding;
619 }
620 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700621 return request;
622 }
623
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700624 /**
625 * Ensures xml start directive/declaration appears in the {@code request}.
626 * @param request RPC request message
627 * @return XML RPC message
628 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700629 private String formatXmlHeader(String request) {
Sean Condon2d647172017-09-19 12:29:13 +0100630 if (!request.contains(XML_HEADER)) {
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700631 //FIXME if application provides his own XML header of different type there is a clash
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200632 if (request.startsWith(LF + HASH)) {
633 request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length());
634 } else {
635 request = XML_HEADER + "\n" + request;
636 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700637 }
638 return request;
639 }
640
641 @Override
642 public String doWrappedRpc(String request) throws NetconfException {
643 StringBuilder rpc = new StringBuilder(XML_HEADER);
644 rpc.append(RPC_OPEN);
645 rpc.append(MESSAGE_ID_STRING);
646 rpc.append(EQUAL);
647 rpc.append("\"");
648 rpc.append(messageIdInteger.get());
649 rpc.append("\" ");
650 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
651 rpc.append(request);
652 rpc.append(RPC_CLOSE).append(NEW_LINE);
653 rpc.append(ENDPATTERN);
654 String reply = sendRequest(rpc.toString());
655 checkReply(reply);
656 return reply;
657 }
658
659 @Override
660 public String get(String request) throws NetconfException {
661 return requestSync(request);
662 }
663
664 @Override
665 public String get(String filterSchema, String withDefaultsMode) throws NetconfException {
666 StringBuilder rpc = new StringBuilder(XML_HEADER);
667 rpc.append(RPC_OPEN);
668 rpc.append(MESSAGE_ID_STRING);
669 rpc.append(EQUAL);
670 rpc.append("\"");
671 rpc.append(messageIdInteger.get());
672 rpc.append("\" ");
673 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
674 rpc.append(GET_OPEN).append(NEW_LINE);
675 if (filterSchema != null) {
676 rpc.append(SUBTREE_FILTER_OPEN).append(NEW_LINE);
677 rpc.append(filterSchema).append(NEW_LINE);
678 rpc.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
679 }
680 if (withDefaultsMode != null) {
681 rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">");
682 rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE);
683 }
684 rpc.append(GET_CLOSE).append(NEW_LINE);
685 rpc.append(RPC_CLOSE).append(NEW_LINE);
686 rpc.append(ENDPATTERN);
687 String reply = sendRequest(rpc.toString());
688 checkReply(reply);
689 return reply;
690 }
691
692 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700693 public String getConfig(DatastoreId netconfTargetConfig) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700694 return getConfig(netconfTargetConfig, null);
695 }
696
697 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700698 public String getConfig(DatastoreId netconfTargetConfig,
699 String configurationSchema) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700700 StringBuilder rpc = new StringBuilder(XML_HEADER);
701 rpc.append("<rpc ");
702 rpc.append(MESSAGE_ID_STRING);
703 rpc.append(EQUAL);
704 rpc.append("\"");
705 rpc.append(messageIdInteger.get());
706 rpc.append("\" ");
707 rpc.append("xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
708 rpc.append("<get-config>\n");
709 rpc.append("<source>\n");
710 rpc.append("<").append(netconfTargetConfig).append("/>");
711 rpc.append("</source>");
712 if (configurationSchema != null) {
713 rpc.append("<filter type=\"subtree\">\n");
714 rpc.append(configurationSchema).append("\n");
715 rpc.append("</filter>\n");
716 }
717 rpc.append("</get-config>\n");
718 rpc.append("</rpc>\n");
719 rpc.append(ENDPATTERN);
720 String reply = sendRequest(rpc.toString());
721 return checkReply(reply) ? reply : "ERROR " + reply;
722 }
723
724 @Override
725 public boolean editConfig(String newConfiguration) throws NetconfException {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200726 if (!newConfiguration.endsWith(ENDPATTERN)) {
727 newConfiguration = newConfiguration + ENDPATTERN;
728 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700729 return checkReply(sendRequest(newConfiguration));
730 }
731
732 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700733 public boolean editConfig(DatastoreId netconfTargetConfig,
734 String mode,
735 String newConfiguration)
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700736 throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700737
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700738 newConfiguration = newConfiguration.trim();
739 StringBuilder rpc = new StringBuilder(XML_HEADER);
740 rpc.append(RPC_OPEN);
741 rpc.append(MESSAGE_ID_STRING);
742 rpc.append(EQUAL);
743 rpc.append("\"");
744 rpc.append(messageIdInteger.get());
745 rpc.append("\" ");
746 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
747 rpc.append(EDIT_CONFIG_OPEN).append("\n");
748 rpc.append(TARGET_OPEN);
749 rpc.append("<").append(netconfTargetConfig).append("/>");
750 rpc.append(TARGET_CLOSE).append("\n");
751 if (mode != null) {
752 rpc.append(DEFAULT_OPERATION_OPEN);
753 rpc.append(mode);
754 rpc.append(DEFAULT_OPERATION_CLOSE).append("\n");
755 }
756 rpc.append(CONFIG_OPEN).append("\n");
757 rpc.append(newConfiguration);
758 rpc.append(CONFIG_CLOSE).append("\n");
759 rpc.append(EDIT_CONFIG_CLOSE).append("\n");
760 rpc.append(RPC_CLOSE);
761 rpc.append(ENDPATTERN);
762 log.debug(rpc.toString());
763 String reply = sendRequest(rpc.toString());
764 return checkReply(reply);
765 }
766
767 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700768 public boolean copyConfig(DatastoreId destination,
769 DatastoreId source)
770 throws NetconfException {
771 return bareCopyConfig(destination.asXml(), source.asXml());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700772 }
773
774 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700775 public boolean copyConfig(DatastoreId netconfTargetConfig,
776 String newConfiguration)
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700777 throws NetconfException {
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700778 return bareCopyConfig(netconfTargetConfig.asXml(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200779 normalizeCopyConfigParam(newConfiguration));
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700780 }
781
782 @Override
783 public boolean copyConfig(String netconfTargetConfig,
784 String newConfiguration) throws NetconfException {
785 return bareCopyConfig(normalizeCopyConfigParam(netconfTargetConfig),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200786 normalizeCopyConfigParam(newConfiguration));
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700787 }
788
789 /**
790 * Normalize String parameter passed to copy-config API.
791 * <p>
792 * Provided for backward compatibility purpose
793 *
794 * @param input passed to copyConfig API
795 * @return XML likely to be suitable for copy-config source or target
796 */
797 private static CharSequence normalizeCopyConfigParam(String input) {
798 input = input.trim();
799 if (input.startsWith("<url")) {
800 return input;
801 } else if (!input.startsWith("<")) {
802 // assume it is a datastore name
803 return DatastoreId.datastore(input).asXml();
804 } else if (!input.startsWith("<config>")) {
805 return "<config>" + input + "</config>";
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700806 }
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700807 return input;
808 }
809
810 private boolean bareCopyConfig(CharSequence target,
811 CharSequence source)
812 throws NetconfException {
813
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700814 StringBuilder rpc = new StringBuilder(XML_HEADER);
815 rpc.append(RPC_OPEN);
816 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
817 rpc.append("<copy-config>");
818 rpc.append("<target>");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700819 rpc.append(target);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700820 rpc.append("</target>");
821 rpc.append("<source>");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700822 rpc.append(source);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700823 rpc.append("</source>");
824 rpc.append("</copy-config>");
825 rpc.append("</rpc>");
826 rpc.append(ENDPATTERN);
827 return checkReply(sendRequest(rpc.toString()));
828 }
829
830 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700831 public boolean deleteConfig(DatastoreId netconfTargetConfig) throws NetconfException {
832 if (netconfTargetConfig.equals(DatastoreId.RUNNING)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700833 log.warn("Target configuration for delete operation can't be \"running\"",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200834 netconfTargetConfig);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700835 return false;
836 }
837 StringBuilder rpc = new StringBuilder(XML_HEADER);
838 rpc.append("<rpc>");
839 rpc.append("<delete-config>");
840 rpc.append("<target>");
841 rpc.append("<").append(netconfTargetConfig).append("/>");
842 rpc.append("</target>");
843 rpc.append("</delete-config>");
844 rpc.append("</rpc>");
845 rpc.append(ENDPATTERN);
846 return checkReply(sendRequest(rpc.toString()));
847 }
848
849 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700850 public boolean lock(DatastoreId configType) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700851 StringBuilder rpc = new StringBuilder(XML_HEADER);
852 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
853 rpc.append("<lock>");
854 rpc.append("<target>");
855 rpc.append("<");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700856 rpc.append(configType.id());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700857 rpc.append("/>");
858 rpc.append("</target>");
859 rpc.append("</lock>");
860 rpc.append("</rpc>");
861 rpc.append(ENDPATTERN);
862 String lockReply = sendRequest(rpc.toString());
863 return checkReply(lockReply);
864 }
865
866 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700867 public boolean unlock(DatastoreId configType) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700868 StringBuilder rpc = new StringBuilder(XML_HEADER);
869 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
870 rpc.append("<unlock>");
871 rpc.append("<target>");
872 rpc.append("<");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700873 rpc.append(configType.id());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700874 rpc.append("/>");
875 rpc.append("</target>");
876 rpc.append("</unlock>");
877 rpc.append("</rpc>");
878 rpc.append(ENDPATTERN);
879 String unlockReply = sendRequest(rpc.toString());
880 return checkReply(unlockReply);
881 }
882
883 @Override
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700884 public boolean close() throws NetconfException {
885 return close(false);
886 }
887
888 private boolean close(boolean force) throws NetconfException {
889 StringBuilder rpc = new StringBuilder();
890 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">");
891 if (force) {
892 rpc.append("<kill-session/>");
893 } else {
894 rpc.append("<close-session/>");
895 }
896 rpc.append("</rpc>");
897 rpc.append(ENDPATTERN);
898 return checkReply(sendRequest(rpc.toString())) || close(true);
899 }
900
901 @Override
902 public String getSessionId() {
903 return sessionID;
904 }
905
906 @Override
907 public Set<String> getDeviceCapabilitiesSet() {
908 return Collections.unmodifiableSet(deviceCapabilities);
909 }
910
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700911 @Override
912 public void setOnosCapabilities(Iterable<String> capabilities) {
913 onosCapabilities = capabilities;
914 }
915
916
917 @Override
918 public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
919 streamHandler.addDeviceEventListener(listener);
920 primaryListeners.add(listener);
921 }
922
923 @Override
924 public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
925 primaryListeners.remove(listener);
926 streamHandler.removeDeviceEventListener(listener);
927 }
928
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700929 private boolean checkReply(String reply) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700930 if (reply != null) {
931 if (!reply.contains("<rpc-error>")) {
932 log.debug("Device {} sent reply {}", deviceInfo, reply);
933 return true;
934 } else if (reply.contains("<ok/>")
935 || (reply.contains("<rpc-error>")
936 && reply.contains("warning"))) {
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700937 // FIXME rpc-error with a warning is considered same as Ok??
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700938 log.debug("Device {} sent reply {}", deviceInfo, reply);
939 return true;
940 }
941 }
942 log.warn("Device {} has error in reply {}", deviceInfo, reply);
943 return false;
944 }
945
Sean Condon7347de92017-07-21 12:17:25 +0100946 protected void publishEvent(NetconfDeviceOutputEvent event) {
947 primaryListeners.forEach(lsnr -> {
948 if (lsnr.isRelevant(event)) {
949 lsnr.event(event);
950 }
951 });
952 }
953
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700954 static class NotificationSession extends NetconfSessionMinaImpl {
955
956 private String notificationFilter;
957
958 NotificationSession(NetconfDeviceInfo deviceInfo)
959 throws NetconfException {
960 super(deviceInfo);
961 }
962
963 @Override
964 protected void startSubscriptionStream(String filterSchema)
965 throws NetconfException {
966
967 notificationFilter = filterSchema;
968 requestSync(createSubscriptionString(filterSchema));
969 }
970
971 @Override
972 public String toString() {
973 return MoreObjects.toStringHelper(getClass())
974 .add("deviceInfo", deviceInfo)
975 .add("sessionID", getSessionId())
976 .add("notificationFilter", notificationFilter)
977 .toString();
978 }
979 }
980
981 /**
982 * Listener attached to child session for notification streaming.
983 * <p>
984 * Forwards all notification event from child session to primary session
985 * listeners.
986 */
987 private final class NotificationForwarder
988 implements NetconfDeviceOutputEventListener {
989
990 @Override
991 public boolean isRelevant(NetconfDeviceOutputEvent event) {
992 return event.type() == Type.DEVICE_NOTIFICATION;
993 }
994
995 @Override
996 public void event(NetconfDeviceOutputEvent event) {
Sean Condon7347de92017-07-21 12:17:25 +0100997 publishEvent(event);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700998 }
999 }
1000
1001 public class NetconfSessionDelegateImpl implements NetconfSessionDelegate {
1002
1003 @Override
1004 public void notify(NetconfDeviceOutputEvent event) {
1005 Optional<Integer> messageId = event.getMessageID();
1006 log.debug("messageID {}, waiting replies messageIDs {}", messageId,
Kamil Stasiak9f59f442017-05-02 11:02:24 +02001007 replies.keySet());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001008 if (!messageId.isPresent()) {
1009 errorReplies.add(event.getMessagePayload());
1010 log.error("Device {} sent error reply {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +02001011 event.getDeviceInfo(), event.getMessagePayload());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001012 return;
1013 }
1014 CompletableFuture<String> completedReply =
Sean Condon7347de92017-07-21 12:17:25 +01001015 replies.get(messageId.get()); // remove(..)?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001016 if (completedReply != null) {
1017 completedReply.complete(event.getMessagePayload());
1018 }
1019 }
1020 }
1021
1022 public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory {
1023
1024 @Override
1025 public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException {
1026 return new NetconfSessionMinaImpl(netconfDeviceInfo);
1027 }
1028 }
Sean Condon54d82432017-07-26 22:27:25 +01001029}