blob: 06fd53a534b5bc89b7e6b674162cc095fb7c5626 [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();
412 }
413 if (subscriptionConnected) {
414 log.debug("Restarting subscription with {}", deviceInfo.getDeviceId());
415 subscriptionConnected = false;
416 startSubscription(notificationFilterSchema);
417 }
Sean Condon7347de92017-07-21 12:17:25 +0100418 } catch (IOException | IllegalStateException e) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700419 log.error("Can't reopen connection for device {}", e.getMessage());
420 throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e);
421 }
422 }
423
424 private void cleanUp() {
425 //makes sure everything is at a clean state.
426 replies.clear();
427 }
428
429 @Override
430 public String requestSync(String request) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700431 String reply = sendRequest(request);
432 checkReply(reply);
433 return reply;
434 }
435
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200436
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700437 // FIXME rename to align with what it actually do
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200438 /**
439 * Validate and format netconf message.
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700440 * - NC1.0 if no EOM sequence present on {@code message}, append.
441 * - NC1.1 chunk-encode given message unless it already is chunk encoded
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200442 *
443 * @param message to format
444 * @return formated message
445 */
446 private String formatNetconfMessage(String message) {
447 if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) {
448 message = formatChunkedMessage(message);
449 } else {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700450 if (!message.endsWith(ENDPATTERN)) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200451 message = message + NEW_LINE + ENDPATTERN;
452 }
453 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700454 return message;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200455 }
456
457 /**
458 * Validate and format message according to chunked framing mechanism.
459 *
460 * @param message to format
461 * @return formated message
462 */
463 private String formatChunkedMessage(String message) {
464 if (message.endsWith(ENDPATTERN)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700465 // message given had Netconf 1.0 EOM pattern -> remove
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200466 message = message.substring(0, message.length() - ENDPATTERN.length());
467 }
468 if (!message.startsWith(LF + HASH)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700469 // chunk encode message
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700470 message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200471 }
472 return message;
473 }
474
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700475 @Override
476 @Deprecated
477 public CompletableFuture<String> request(String request) {
478 return streamHandler.sendMessage(request);
479 }
480
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700481 /**
482 * {@inheritDoc}
483 * <p>
484 * FIXME Note: as of 1.12.0
485 * {@code request} must not include message-id, this method will assign
486 * and insert message-id on it's own.
487 * Will require ONOS-7019 to remove this limitation.
488 */
489 @Override
490 public CompletableFuture<String> rpc(String request) {
491
492 String rpc = request;
493 // - assign message-id
494 int msgId = messageIdInteger.incrementAndGet();
495 // - re-write request to insert message-id
496 // FIXME avoid using formatRequestMessageId
497 rpc = formatRequestMessageId(rpc, msgId);
498 // - ensure it contains XML header
499 rpc = formatXmlHeader(rpc);
500 // - use chunked framing if talking to NC 1.1 device
501 // FIXME avoid using formatNetconfMessage
502 rpc = formatNetconfMessage(rpc);
503
504 // TODO session liveness check & recovery
505
506 log.debug("Sending {} to {}", rpc, this.deviceInfo.getDeviceId());
507 return streamHandler.sendMessage(rpc, msgId)
508 .handleAsync((reply, t) -> {
509 if (t != null) {
510 // secure transport-layer error
511 // cannot use NetconfException, which is
512 // checked Exception.
513 throw new NetconfTransportException(t);
514 } else {
515 // FIXME avoid using checkReply, error handling is weird
516 checkReply(reply);
517 return reply;
518 }
519 }, SharedExecutors.getPoolThreadExecutor());
520 }
521
Sean Condon54d82432017-07-26 22:27:25 +0100522 @Override
523 public int timeoutConnectSec() {
524 return connectTimeout;
525 }
526
527 @Override
528 public int timeoutReplySec() {
529 return replyTimeout;
530 }
531
532 @Override
533 public int timeoutIdleSec() {
534 return idleTimeout;
535 }
536
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700537 private CompletableFuture<String> request(String request, int messageId) {
538 return streamHandler.sendMessage(request, messageId);
539 }
540
541 private String sendRequest(String request) throws NetconfException {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700542 // FIXME probably chunk-encoding too early
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200543 request = formatNetconfMessage(request);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700544 return sendRequest(request, false);
545 }
546
547 private String sendRequest(String request, boolean isHello) throws NetconfException {
548 checkAndReestablish();
549 int messageId = -1;
550 if (!isHello) {
551 messageId = messageIdInteger.getAndIncrement();
552 }
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700553 // FIXME potentially re-writing chunked encoded String?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700554 request = formatXmlHeader(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200555 request = formatRequestMessageId(request, messageId);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700556 log.debug("Sending request to NETCONF with timeout {} for {}",
557 replyTimeout, deviceInfo.name());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700558 CompletableFuture<String> futureReply = request(request, messageId);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700559 String rp;
560 try {
561 rp = futureReply.get(replyTimeout, TimeUnit.SECONDS);
Sean Condon7347de92017-07-21 12:17:25 +0100562 replies.remove(messageId); // Why here???
563 } catch (InterruptedException e) {
564 Thread.currentThread().interrupt();
565 throw new NetconfException("Interrupted waiting for reply for request" + request, e);
566 } catch (TimeoutException e) {
Sean Condon54d82432017-07-26 22:27:25 +0100567 throw new NetconfException("Timed out waiting for reply for request " +
568 request + " after " + replyTimeout + " sec.", e);
Sean Condon7347de92017-07-21 12:17:25 +0100569 } catch (ExecutionException e) {
570 log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e);
571 try {
572 session.close();
573 channel.close(); //Closes the socket which should interrupt NetconfStreamThread
574 client.close();
575 } catch (IOException ioe) {
576 log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe);
577 }
578 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
579 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
580 null, "Closed due to unexpected error " + e.getCause(),
581 Optional.of(-1), deviceInfo);
582 publishEvent(event);
583 errorReplies.clear(); // move to cleanUp()?
584 cleanUp();
585
586 throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo +
587 " for request " + request, e);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700588 }
589 log.debug("Result {} from request {} to device {}", rp, request, deviceInfo);
590 return rp.trim();
591 }
592
593 private String formatRequestMessageId(String request, int messageId) {
594 if (request.contains(MESSAGE_ID_STRING)) {
595 //FIXME if application provides his own counting of messages this fails that count
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700596 // FIXME assumes message-id is integer. RFC6241 allows anything as long as it is allowed in XML
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700597 request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200598 MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\"");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700599 } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) {
600 //FIXME find out a better way to enforce the presence of message-id
601 request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\""
602 + messageId + "\"" + ">");
603 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700604 request = updateRequestLength(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200605 return request;
606 }
607
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700608 private String updateRequestLength(String request) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200609 if (request.contains(LF + HASH + HASH + LF)) {
610 int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]);
611 String rpcWithEnding = request.substring(request.indexOf('<'));
612 String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0];
613 int newLen = 0;
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700614 newLen = firstBlock.getBytes(UTF_8).length;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200615 if (oldLen != newLen) {
616 return LF + HASH + newLen + LF + rpcWithEnding;
617 }
618 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700619 return request;
620 }
621
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700622 /**
623 * Ensures xml start directive/declaration appears in the {@code request}.
624 * @param request RPC request message
625 * @return XML RPC message
626 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700627 private String formatXmlHeader(String request) {
Sean Condon2d647172017-09-19 12:29:13 +0100628 if (!request.contains(XML_HEADER)) {
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700629 //FIXME if application provides his own XML header of different type there is a clash
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200630 if (request.startsWith(LF + HASH)) {
631 request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length());
632 } else {
633 request = XML_HEADER + "\n" + request;
634 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700635 }
636 return request;
637 }
638
639 @Override
640 public String doWrappedRpc(String request) throws NetconfException {
641 StringBuilder rpc = new StringBuilder(XML_HEADER);
642 rpc.append(RPC_OPEN);
643 rpc.append(MESSAGE_ID_STRING);
644 rpc.append(EQUAL);
645 rpc.append("\"");
646 rpc.append(messageIdInteger.get());
647 rpc.append("\" ");
648 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
649 rpc.append(request);
650 rpc.append(RPC_CLOSE).append(NEW_LINE);
651 rpc.append(ENDPATTERN);
652 String reply = sendRequest(rpc.toString());
653 checkReply(reply);
654 return reply;
655 }
656
657 @Override
658 public String get(String request) throws NetconfException {
659 return requestSync(request);
660 }
661
662 @Override
663 public String get(String filterSchema, String withDefaultsMode) throws NetconfException {
664 StringBuilder rpc = new StringBuilder(XML_HEADER);
665 rpc.append(RPC_OPEN);
666 rpc.append(MESSAGE_ID_STRING);
667 rpc.append(EQUAL);
668 rpc.append("\"");
669 rpc.append(messageIdInteger.get());
670 rpc.append("\" ");
671 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
672 rpc.append(GET_OPEN).append(NEW_LINE);
673 if (filterSchema != null) {
674 rpc.append(SUBTREE_FILTER_OPEN).append(NEW_LINE);
675 rpc.append(filterSchema).append(NEW_LINE);
676 rpc.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
677 }
678 if (withDefaultsMode != null) {
679 rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">");
680 rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE);
681 }
682 rpc.append(GET_CLOSE).append(NEW_LINE);
683 rpc.append(RPC_CLOSE).append(NEW_LINE);
684 rpc.append(ENDPATTERN);
685 String reply = sendRequest(rpc.toString());
686 checkReply(reply);
687 return reply;
688 }
689
690 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700691 public String getConfig(DatastoreId netconfTargetConfig) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700692 return getConfig(netconfTargetConfig, null);
693 }
694
695 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700696 public String getConfig(DatastoreId netconfTargetConfig,
697 String configurationSchema) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700698 StringBuilder rpc = new StringBuilder(XML_HEADER);
699 rpc.append("<rpc ");
700 rpc.append(MESSAGE_ID_STRING);
701 rpc.append(EQUAL);
702 rpc.append("\"");
703 rpc.append(messageIdInteger.get());
704 rpc.append("\" ");
705 rpc.append("xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
706 rpc.append("<get-config>\n");
707 rpc.append("<source>\n");
708 rpc.append("<").append(netconfTargetConfig).append("/>");
709 rpc.append("</source>");
710 if (configurationSchema != null) {
711 rpc.append("<filter type=\"subtree\">\n");
712 rpc.append(configurationSchema).append("\n");
713 rpc.append("</filter>\n");
714 }
715 rpc.append("</get-config>\n");
716 rpc.append("</rpc>\n");
717 rpc.append(ENDPATTERN);
718 String reply = sendRequest(rpc.toString());
719 return checkReply(reply) ? reply : "ERROR " + reply;
720 }
721
722 @Override
723 public boolean editConfig(String newConfiguration) throws NetconfException {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200724 if (!newConfiguration.endsWith(ENDPATTERN)) {
725 newConfiguration = newConfiguration + ENDPATTERN;
726 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700727 return checkReply(sendRequest(newConfiguration));
728 }
729
730 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700731 public boolean editConfig(DatastoreId netconfTargetConfig,
732 String mode,
733 String newConfiguration)
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700734 throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700735
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700736 newConfiguration = newConfiguration.trim();
737 StringBuilder rpc = new StringBuilder(XML_HEADER);
738 rpc.append(RPC_OPEN);
739 rpc.append(MESSAGE_ID_STRING);
740 rpc.append(EQUAL);
741 rpc.append("\"");
742 rpc.append(messageIdInteger.get());
743 rpc.append("\" ");
744 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
745 rpc.append(EDIT_CONFIG_OPEN).append("\n");
746 rpc.append(TARGET_OPEN);
747 rpc.append("<").append(netconfTargetConfig).append("/>");
748 rpc.append(TARGET_CLOSE).append("\n");
749 if (mode != null) {
750 rpc.append(DEFAULT_OPERATION_OPEN);
751 rpc.append(mode);
752 rpc.append(DEFAULT_OPERATION_CLOSE).append("\n");
753 }
754 rpc.append(CONFIG_OPEN).append("\n");
755 rpc.append(newConfiguration);
756 rpc.append(CONFIG_CLOSE).append("\n");
757 rpc.append(EDIT_CONFIG_CLOSE).append("\n");
758 rpc.append(RPC_CLOSE);
759 rpc.append(ENDPATTERN);
760 log.debug(rpc.toString());
761 String reply = sendRequest(rpc.toString());
762 return checkReply(reply);
763 }
764
765 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700766 public boolean copyConfig(DatastoreId destination,
767 DatastoreId source)
768 throws NetconfException {
769 return bareCopyConfig(destination.asXml(), source.asXml());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700770 }
771
772 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700773 public boolean copyConfig(DatastoreId netconfTargetConfig,
774 String newConfiguration)
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700775 throws NetconfException {
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700776 return bareCopyConfig(netconfTargetConfig.asXml(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200777 normalizeCopyConfigParam(newConfiguration));
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700778 }
779
780 @Override
781 public boolean copyConfig(String netconfTargetConfig,
782 String newConfiguration) throws NetconfException {
783 return bareCopyConfig(normalizeCopyConfigParam(netconfTargetConfig),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200784 normalizeCopyConfigParam(newConfiguration));
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700785 }
786
787 /**
788 * Normalize String parameter passed to copy-config API.
789 * <p>
790 * Provided for backward compatibility purpose
791 *
792 * @param input passed to copyConfig API
793 * @return XML likely to be suitable for copy-config source or target
794 */
795 private static CharSequence normalizeCopyConfigParam(String input) {
796 input = input.trim();
797 if (input.startsWith("<url")) {
798 return input;
799 } else if (!input.startsWith("<")) {
800 // assume it is a datastore name
801 return DatastoreId.datastore(input).asXml();
802 } else if (!input.startsWith("<config>")) {
803 return "<config>" + input + "</config>";
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700804 }
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700805 return input;
806 }
807
808 private boolean bareCopyConfig(CharSequence target,
809 CharSequence source)
810 throws NetconfException {
811
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700812 StringBuilder rpc = new StringBuilder(XML_HEADER);
813 rpc.append(RPC_OPEN);
814 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
815 rpc.append("<copy-config>");
816 rpc.append("<target>");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700817 rpc.append(target);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700818 rpc.append("</target>");
819 rpc.append("<source>");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700820 rpc.append(source);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700821 rpc.append("</source>");
822 rpc.append("</copy-config>");
823 rpc.append("</rpc>");
824 rpc.append(ENDPATTERN);
825 return checkReply(sendRequest(rpc.toString()));
826 }
827
828 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700829 public boolean deleteConfig(DatastoreId netconfTargetConfig) throws NetconfException {
830 if (netconfTargetConfig.equals(DatastoreId.RUNNING)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700831 log.warn("Target configuration for delete operation can't be \"running\"",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200832 netconfTargetConfig);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700833 return false;
834 }
835 StringBuilder rpc = new StringBuilder(XML_HEADER);
836 rpc.append("<rpc>");
837 rpc.append("<delete-config>");
838 rpc.append("<target>");
839 rpc.append("<").append(netconfTargetConfig).append("/>");
840 rpc.append("</target>");
841 rpc.append("</delete-config>");
842 rpc.append("</rpc>");
843 rpc.append(ENDPATTERN);
844 return checkReply(sendRequest(rpc.toString()));
845 }
846
847 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700848 public boolean lock(DatastoreId configType) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700849 StringBuilder rpc = new StringBuilder(XML_HEADER);
850 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
851 rpc.append("<lock>");
852 rpc.append("<target>");
853 rpc.append("<");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700854 rpc.append(configType.id());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700855 rpc.append("/>");
856 rpc.append("</target>");
857 rpc.append("</lock>");
858 rpc.append("</rpc>");
859 rpc.append(ENDPATTERN);
860 String lockReply = sendRequest(rpc.toString());
861 return checkReply(lockReply);
862 }
863
864 @Override
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700865 public boolean unlock(DatastoreId configType) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700866 StringBuilder rpc = new StringBuilder(XML_HEADER);
867 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
868 rpc.append("<unlock>");
869 rpc.append("<target>");
870 rpc.append("<");
Yuta HIGUCHI26c397c2017-05-19 12:52:28 -0700871 rpc.append(configType.id());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700872 rpc.append("/>");
873 rpc.append("</target>");
874 rpc.append("</unlock>");
875 rpc.append("</rpc>");
876 rpc.append(ENDPATTERN);
877 String unlockReply = sendRequest(rpc.toString());
878 return checkReply(unlockReply);
879 }
880
881 @Override
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700882 public boolean close() throws NetconfException {
883 return close(false);
884 }
885
886 private boolean close(boolean force) throws NetconfException {
887 StringBuilder rpc = new StringBuilder();
888 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">");
889 if (force) {
890 rpc.append("<kill-session/>");
891 } else {
892 rpc.append("<close-session/>");
893 }
894 rpc.append("</rpc>");
895 rpc.append(ENDPATTERN);
896 return checkReply(sendRequest(rpc.toString())) || close(true);
897 }
898
899 @Override
900 public String getSessionId() {
901 return sessionID;
902 }
903
904 @Override
905 public Set<String> getDeviceCapabilitiesSet() {
906 return Collections.unmodifiableSet(deviceCapabilities);
907 }
908
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700909 @Override
910 public void setOnosCapabilities(Iterable<String> capabilities) {
911 onosCapabilities = capabilities;
912 }
913
914
915 @Override
916 public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
917 streamHandler.addDeviceEventListener(listener);
918 primaryListeners.add(listener);
919 }
920
921 @Override
922 public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
923 primaryListeners.remove(listener);
924 streamHandler.removeDeviceEventListener(listener);
925 }
926
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700927 private boolean checkReply(String reply) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700928 if (reply != null) {
929 if (!reply.contains("<rpc-error>")) {
930 log.debug("Device {} sent reply {}", deviceInfo, reply);
931 return true;
932 } else if (reply.contains("<ok/>")
933 || (reply.contains("<rpc-error>")
934 && reply.contains("warning"))) {
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700935 // FIXME rpc-error with a warning is considered same as Ok??
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700936 log.debug("Device {} sent reply {}", deviceInfo, reply);
937 return true;
938 }
939 }
940 log.warn("Device {} has error in reply {}", deviceInfo, reply);
941 return false;
942 }
943
Sean Condon7347de92017-07-21 12:17:25 +0100944 protected void publishEvent(NetconfDeviceOutputEvent event) {
945 primaryListeners.forEach(lsnr -> {
946 if (lsnr.isRelevant(event)) {
947 lsnr.event(event);
948 }
949 });
950 }
951
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700952 static class NotificationSession extends NetconfSessionMinaImpl {
953
954 private String notificationFilter;
955
956 NotificationSession(NetconfDeviceInfo deviceInfo)
957 throws NetconfException {
958 super(deviceInfo);
959 }
960
961 @Override
962 protected void startSubscriptionStream(String filterSchema)
963 throws NetconfException {
964
965 notificationFilter = filterSchema;
966 requestSync(createSubscriptionString(filterSchema));
967 }
968
969 @Override
970 public String toString() {
971 return MoreObjects.toStringHelper(getClass())
972 .add("deviceInfo", deviceInfo)
973 .add("sessionID", getSessionId())
974 .add("notificationFilter", notificationFilter)
975 .toString();
976 }
977 }
978
979 /**
980 * Listener attached to child session for notification streaming.
981 * <p>
982 * Forwards all notification event from child session to primary session
983 * listeners.
984 */
985 private final class NotificationForwarder
986 implements NetconfDeviceOutputEventListener {
987
988 @Override
989 public boolean isRelevant(NetconfDeviceOutputEvent event) {
990 return event.type() == Type.DEVICE_NOTIFICATION;
991 }
992
993 @Override
994 public void event(NetconfDeviceOutputEvent event) {
Sean Condon7347de92017-07-21 12:17:25 +0100995 publishEvent(event);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700996 }
997 }
998
999 public class NetconfSessionDelegateImpl implements NetconfSessionDelegate {
1000
1001 @Override
1002 public void notify(NetconfDeviceOutputEvent event) {
1003 Optional<Integer> messageId = event.getMessageID();
1004 log.debug("messageID {}, waiting replies messageIDs {}", messageId,
Kamil Stasiak9f59f442017-05-02 11:02:24 +02001005 replies.keySet());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001006 if (!messageId.isPresent()) {
1007 errorReplies.add(event.getMessagePayload());
1008 log.error("Device {} sent error reply {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +02001009 event.getDeviceInfo(), event.getMessagePayload());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001010 return;
1011 }
1012 CompletableFuture<String> completedReply =
Sean Condon7347de92017-07-21 12:17:25 +01001013 replies.get(messageId.get()); // remove(..)?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -07001014 if (completedReply != null) {
1015 completedReply.complete(event.getMessagePayload());
1016 }
1017 }
1018 }
1019
1020 public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory {
1021
1022 @Override
1023 public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException {
1024 return new NetconfSessionMinaImpl(netconfDeviceInfo);
1025 }
1026 }
Sean Condon54d82432017-07-26 22:27:25 +01001027}