blob: 261adea1f4c50eff50358162d65b7f8526da0e02 [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;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070024import com.google.common.collect.Sets;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070025import org.apache.sshd.client.SshClient;
26import org.apache.sshd.client.channel.ClientChannel;
27import org.apache.sshd.client.future.ConnectFuture;
28import org.apache.sshd.client.future.OpenFuture;
29import org.apache.sshd.client.session.ClientSession;
Sean Condon7347de92017-07-21 12:17:25 +010030import org.apache.sshd.common.FactoryManager;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070031import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
Holger Schulz092cbbf2017-08-31 17:52:30 +020032import org.bouncycastle.jce.provider.BouncyCastleProvider;
Holger Schulz092cbbf2017-08-31 17:52:30 +020033import org.bouncycastle.openssl.PEMKeyPair;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070034import org.bouncycastle.openssl.PEMParser;
Holger Schulz092cbbf2017-08-31 17:52:30 +020035import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070036import org.onlab.osgi.DefaultServiceDirectory;
37import org.onlab.osgi.ServiceDirectory;
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070038import org.onlab.util.SharedExecutors;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070039import org.onosproject.net.DeviceId;
40import org.onosproject.net.driver.Driver;
41import org.onosproject.net.driver.DriverService;
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -070042import org.onosproject.netconf.AbstractNetconfSession;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070043import org.onosproject.netconf.NetconfDeviceInfo;
44import org.onosproject.netconf.NetconfDeviceOutputEvent;
45import org.onosproject.netconf.NetconfDeviceOutputEvent.Type;
46import org.onosproject.netconf.NetconfDeviceOutputEventListener;
47import org.onosproject.netconf.NetconfException;
48import org.onosproject.netconf.NetconfSession;
49import org.onosproject.netconf.NetconfSessionFactory;
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070050import org.onosproject.netconf.NetconfTransportException;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070051import org.slf4j.Logger;
Yuta HIGUCHI15677982017-08-16 15:50:29 -070052
Holger Schulz092cbbf2017-08-31 17:52:30 +020053import java.io.CharArrayReader;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070054import java.io.IOException;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070055import java.security.KeyFactory;
56import java.security.KeyPair;
57import java.security.NoSuchAlgorithmException;
58import java.security.PublicKey;
59import java.security.spec.InvalidKeySpecException;
60import java.security.spec.X509EncodedKeySpec;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070061import java.util.ArrayList;
62import java.util.Arrays;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070063import java.util.Collection;
64import java.util.Collections;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070065import java.util.LinkedHashSet;
66import java.util.List;
67import java.util.Map;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070068import java.util.Optional;
quan PHAM VAN32d70e52018-08-01 17:35:30 -070069import java.util.Set;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070070import java.util.concurrent.CompletableFuture;
71import java.util.concurrent.ConcurrentHashMap;
72import java.util.concurrent.CopyOnWriteArrayList;
73import java.util.concurrent.ExecutionException;
74import java.util.concurrent.TimeUnit;
75import java.util.concurrent.TimeoutException;
76import java.util.concurrent.atomic.AtomicInteger;
77import java.util.regex.Matcher;
78import java.util.regex.Pattern;
79
quan PHAM VAN32d70e52018-08-01 17:35:30 -070080import static java.nio.charset.StandardCharsets.UTF_8;
81import static org.slf4j.LoggerFactory.getLogger;
82
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070083/**
84 * Implementation of a NETCONF session to talk to a device.
85 */
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -070086public class NetconfSessionMinaImpl extends AbstractNetconfSession {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070087
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -070088 private static final Logger log = getLogger(NetconfSessionMinaImpl.class);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070089
Yuta HIGUCHI371667d2017-09-05 17:30:51 -070090 /**
91 * NC 1.0, RFC4742 EOM sequence.
92 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -070093 private static final String ENDPATTERN = "]]>]]>";
94 private static final String MESSAGE_ID_STRING = "message-id";
95 private static final String HELLO = "<hello";
96 private static final String NEW_LINE = "\n";
97 private static final String END_OF_RPC_OPEN_TAG = "\">";
98 private static final String EQUAL = "=";
99 private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"";
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700100 private static final String SUBTREE_FILTER_CLOSE = "</filter>";
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700101 // FIXME hard coded namespace nc
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700102 private static final String XML_HEADER =
103 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -0700104
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700105 // FIXME hard coded namespace base10
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700106 private static final String SUBSCRIPTION_SUBTREE_FILTER_OPEN =
107 "<filter xmlns:base10=\"urn:ietf:params:xml:ns:netconf:base:1.0\" base10:type=\"subtree\">";
108
109 private static final String INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0";
110
111 private static final String CAPABILITY_REGEX = "<capability>\\s*(.*?)\\s*</capability>";
112 private static final Pattern CAPABILITY_REGEX_PATTERN = Pattern.compile(CAPABILITY_REGEX);
113
114 private static final String SESSION_ID_REGEX = "<session-id>\\s*(.*?)\\s*</session-id>";
115 private static final Pattern SESSION_ID_REGEX_PATTERN = Pattern.compile(SESSION_ID_REGEX);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200116 private static final String HASH = "#";
117 private static final String LF = "\n";
118 private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n";
119 private static final String NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0";
120 private static final String NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1";
quan PHAM VAN32d70e52018-08-01 17:35:30 -0700121 private static final String NETCONF_CLIENT_CAPABILITY = "netconfClientCapability";
Laszlo Pappbdb64082018-09-11 12:21:29 +0100122 private static final String NOTIFICATION_STREAM = "notificationStream";
quan PHAM VAN32d70e52018-08-01 17:35:30 -0700123
124 private static ServiceDirectory directory = new DefaultServiceDirectory();
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700125
126 private String sessionID;
127 private final AtomicInteger messageIdInteger = new AtomicInteger(1);
128 protected final NetconfDeviceInfo deviceInfo;
129 private Iterable<String> onosCapabilities =
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200130 ImmutableList.of(NETCONF_10_CAPABILITY, NETCONF_11_CAPABILITY);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700131
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700132 private final Set<String> deviceCapabilities = new LinkedHashSet<>();
133 private NetconfStreamHandler streamHandler;
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700134 // FIXME ONOS-7019 key type should be revised to a String, see RFC6241
135 /**
136 * Message-ID and corresponding Future waiting for response.
137 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700138 private Map<Integer, CompletableFuture<String>> replies;
Sean Condon7347de92017-07-21 12:17:25 +0100139 private List<String> errorReplies; // Not sure why we need this?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700140 private boolean subscriptionConnected = false;
141 private String notificationFilterSchema = null;
142
143 private final Collection<NetconfDeviceOutputEventListener> primaryListeners =
144 new CopyOnWriteArrayList<>();
145 private final Collection<NetconfSession> children =
146 new CopyOnWriteArrayList<>();
147
Sean Condon54d82432017-07-26 22:27:25 +0100148 private int connectTimeout;
149 private int replyTimeout;
150 private int idleTimeout;
151
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700152 private ClientChannel channel = null;
153 private ClientSession session = null;
154 private SshClient client = null;
155
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700156 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
157 this.deviceInfo = deviceInfo;
158 replies = new ConcurrentHashMap<>();
159 errorReplies = new ArrayList<>();
quan PHAM VAN32d70e52018-08-01 17:35:30 -0700160 Set<String> capabilities = getClientCapabilites(deviceInfo.getDeviceId());
161 if (!capabilities.isEmpty()) {
162 capabilities.addAll(Sets.newHashSet(onosCapabilities));
163 setOnosCapabilities(capabilities);
164 }
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700165 // FIXME should not immediately start session on construction
166 // setOnosCapabilities() is useless due to this behavior
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700167 startConnection();
168 }
169
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200170 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo, List<String> capabilities) throws NetconfException {
171 this.deviceInfo = deviceInfo;
172 replies = new ConcurrentHashMap<>();
173 errorReplies = new ArrayList<>();
174 setOnosCapabilities(capabilities);
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700175 // FIXME should not immediately start session on construction
176 // setOnosCapabilities() is useless due to this behavior
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200177 startConnection();
178 }
179
quan PHAM VAN32d70e52018-08-01 17:35:30 -0700180 /**
181 * Get the list of the netconf client capabilities from device driver property.
182 *
183 * @param deviceId the deviceID for which to recover the capabilities from the driver.
184 * @return the String list of clientCapability property, or null if it is not configured
185 */
186 public Set<String> getClientCapabilites(DeviceId deviceId) {
187 Set<String> capabilities = new LinkedHashSet<>();
188 DriverService driverService = directory.get(DriverService.class);
189 Driver driver = driverService.getDriver(deviceId);
190 if (driver == null) {
191 return capabilities;
192 }
193 String clientCapabilities = driver.getProperty(NETCONF_CLIENT_CAPABILITY);
194 if (clientCapabilities == null) {
195 return capabilities;
196 }
197 String[] textStr = clientCapabilities.split("\\|");
198 capabilities.addAll(Arrays.asList(textStr));
199 return capabilities;
200 }
201
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700202 private void startConnection() throws NetconfException {
Sean Condon54d82432017-07-26 22:27:25 +0100203 connectTimeout = deviceInfo.getConnectTimeoutSec().orElse(
204 NetconfControllerImpl.netconfConnectTimeout);
205 replyTimeout = deviceInfo.getReplyTimeoutSec().orElse(
206 NetconfControllerImpl.netconfReplyTimeout);
207 idleTimeout = deviceInfo.getIdleTimeoutSec().orElse(
208 NetconfControllerImpl.netconfIdleTimeout);
209 log.info("Connecting to {} with timeouts C:{}, R:{}, I:{}", deviceInfo,
210 connectTimeout, replyTimeout, idleTimeout);
211
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700212 try {
213 startClient();
214 } catch (IOException e) {
215 throw new NetconfException("Failed to establish SSH with device " + deviceInfo, e);
216 }
217 }
218
219 private void startClient() throws IOException {
Yuta HIGUCHI2ee4fba2018-06-12 16:21:06 -0700220 log.info("Creating NETCONF session to {}",
221 deviceInfo.getDeviceId());
222
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700223 client = SshClient.setUpDefaultClient();
Sean Condon7347de92017-07-21 12:17:25 +0100224 client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100225 TimeUnit.SECONDS.toMillis(idleTimeout));
Sean Condon7347de92017-07-21 12:17:25 +0100226 client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100227 TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700228 client.start();
229 client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
230 startSession();
231 }
232
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -0700233 //TODO: Remove the default methods already implemented in NetconfSession
234
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700235 // FIXME blocking
236 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700237 private void startSession() throws IOException {
238 final ConnectFuture connectFuture;
239 connectFuture = client.connect(deviceInfo.name(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200240 deviceInfo.ip().toString(),
241 deviceInfo.port())
Sean Condon54d82432017-07-26 22:27:25 +0100242 .verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700243 session = connectFuture.getSession();
244 //Using the device ssh key if possible
245 if (deviceInfo.getKey() != null) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700246 try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
247 JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
248 try {
249 KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
250 session.addPublicKeyIdentity(kp);
251 } catch (IOException e) {
252 throw new NetconfException("Failed to authenticate session with device " +
253 deviceInfo + "check key to be a valid key", e);
254 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700255 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700256 } else {
257 session.addPasswordIdentity(deviceInfo.password());
258 }
Sean Condon54d82432017-07-26 22:27:25 +0100259 session.auth().verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700260 Set<ClientSession.ClientSessionEvent> event = session.waitFor(
261 ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200262 ClientSession.ClientSessionEvent.CLOSED,
263 ClientSession.ClientSessionEvent.AUTHED), 0);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700264
265 if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
266 log.debug("Session closed {} {}", event, session.isClosed());
267 throw new NetconfException("Failed to authenticate session with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200268 deviceInfo + "check the user/pwd or key");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700269 }
270 openChannel();
271 }
272
273 private PublicKey getPublicKey(byte[] keyBytes, String type)
274 throws NoSuchAlgorithmException, InvalidKeySpecException {
275
276 X509EncodedKeySpec spec =
277 new X509EncodedKeySpec(keyBytes);
278 KeyFactory kf = KeyFactory.getInstance(type);
279 return kf.generatePublic(spec);
280 }
281
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700282 // FIXME blocking
283 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700284 private void openChannel() throws IOException {
285 channel = session.createSubsystemChannel("netconf");
286 OpenFuture channelFuture = channel.open();
Sean Condon54d82432017-07-26 22:27:25 +0100287 if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700288 if (channelFuture.isOpened()) {
289 streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200290 channel.getInvertedErr(), deviceInfo,
291 new NetconfSessionDelegateImpl(), replies);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700292 } else {
293 throw new NetconfException("Failed to open channel with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200294 deviceInfo);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700295 }
296 sendHello();
297 }
298 }
299
300
301 @Beta
302 protected void startSubscriptionStream(String filterSchema) throws NetconfException {
303 boolean openNewSession = false;
304 if (!deviceCapabilities.contains(INTERLEAVE_CAPABILITY_STRING)) {
305 log.info("Device {} doesn't support interleave, creating child session", deviceInfo);
306 openNewSession = true;
307
308 } else if (subscriptionConnected &&
309 notificationFilterSchema != null &&
310 !Objects.equal(filterSchema, notificationFilterSchema)) {
311 // interleave supported and existing filter is NOT "no filtering"
312 // and was requested with different filtering schema
313 log.info("Cannot use existing session for subscription {} ({})",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200314 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700315 openNewSession = true;
316 }
317
318 if (openNewSession) {
319 log.info("Creating notification session to {} with filter {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200320 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700321 NetconfSession child = new NotificationSession(deviceInfo);
322
323 child.addDeviceOutputListener(new NotificationForwarder());
324
325 child.startSubscription(filterSchema);
326 children.add(child);
327 return;
328 }
329
330 // request to start interleaved notification session
331 String reply = sendRequest(createSubscriptionString(filterSchema));
332 if (!checkReply(reply)) {
333 throw new NetconfException("Subscription not successful with device "
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200334 + deviceInfo + " with reply " + reply);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700335 }
336 subscriptionConnected = true;
337 }
338
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700339 @Beta
340 @Override
341 public void startSubscription(String filterSchema) throws NetconfException {
342 if (!subscriptionConnected) {
343 notificationFilterSchema = filterSchema;
344 startSubscriptionStream(filterSchema);
345 }
346 streamHandler.setEnableNotifications(true);
347 }
348
349 @Beta
350 protected String createSubscriptionString(String filterSchema) {
351 StringBuilder subscriptionbuffer = new StringBuilder();
352 subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
353 subscriptionbuffer.append(" <create-subscription\n");
354 subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n");
Laszlo Pappbdb64082018-09-11 12:21:29 +0100355 DriverService driverService = directory.get(DriverService.class);
356 Driver driver = driverService.getDriver(deviceInfo.getDeviceId());
357 if (driver != null) {
358 String stream = driver.getProperty(NOTIFICATION_STREAM);
359 if (stream != null) {
360 subscriptionbuffer.append(" <stream>");
361 subscriptionbuffer.append(stream);
362 subscriptionbuffer.append("</stream>\n");
363 }
364 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700365 // FIXME Only subtree filtering supported at the moment.
366 if (filterSchema != null) {
367 subscriptionbuffer.append(" ");
368 subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE);
369 subscriptionbuffer.append(filterSchema).append(NEW_LINE);
370 subscriptionbuffer.append(" ");
371 subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
372 }
373 subscriptionbuffer.append(" </create-subscription>\n");
374 subscriptionbuffer.append("</rpc>\n");
375 subscriptionbuffer.append(ENDPATTERN);
376 return subscriptionbuffer.toString();
377 }
378
379 @Override
380 public void endSubscription() throws NetconfException {
381 if (subscriptionConnected) {
382 streamHandler.setEnableNotifications(false);
383 } else {
384 throw new NetconfException("Subscription does not exist.");
385 }
386 }
387
388 private void sendHello() throws NetconfException {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700389 String serverHelloResponse = sendRequest(createHelloString(), true);
390 Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700391 while (capabilityMatcher.find()) {
392 deviceCapabilities.add(capabilityMatcher.group(1));
393 }
394 sessionID = String.valueOf(-1);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700395 Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700396 if (sessionIDMatcher.find()) {
397 sessionID = sessionIDMatcher.group(1);
398 } else {
399 throw new NetconfException("Missing SessionID in server hello " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200400 "reponse.");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700401 }
402
403 }
404
405 private String createHelloString() {
406 StringBuilder hellobuffer = new StringBuilder();
407 hellobuffer.append(XML_HEADER);
408 hellobuffer.append("\n");
409 hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
410 hellobuffer.append(" <capabilities>\n");
411 onosCapabilities.forEach(
412 cap -> hellobuffer.append(" <capability>")
413 .append(cap)
414 .append("</capability>\n"));
415 hellobuffer.append(" </capabilities>\n");
416 hellobuffer.append("</hello>\n");
417 hellobuffer.append(ENDPATTERN);
418 return hellobuffer.toString();
419
420 }
421
422 @Override
423 public void checkAndReestablish() throws NetconfException {
424 try {
zhongguo zhao98bb37a2018-08-28 16:17:06 +0800425 if (client.isClosed() || client.isClosing()) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700426 log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId());
427 cleanUp();
428 startConnection();
zhongguo zhao98bb37a2018-08-28 16:17:06 +0800429 } else if (session.isClosed() || session.isClosing()) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700430 log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId());
431 cleanUp();
432 startSession();
zhongguo zhao98bb37a2018-08-28 16:17:06 +0800433 } else if (channel.isClosed() || channel.isClosing()) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700434 log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId());
435 cleanUp();
436 openChannel();
Andrea Campanella856f3132017-10-23 15:46:36 +0200437 } else {
438 return;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700439 }
440 if (subscriptionConnected) {
441 log.debug("Restarting subscription with {}", deviceInfo.getDeviceId());
442 subscriptionConnected = false;
443 startSubscription(notificationFilterSchema);
444 }
Sean Condon7347de92017-07-21 12:17:25 +0100445 } catch (IOException | IllegalStateException e) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700446 log.error("Can't reopen connection for device {}", e.getMessage());
447 throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e);
448 }
449 }
450
451 private void cleanUp() {
452 //makes sure everything is at a clean state.
453 replies.clear();
454 }
455
456 @Override
457 public String requestSync(String request) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700458 String reply = sendRequest(request);
Kim JeongWoo8b03bc52018-08-10 16:50:23 +0900459 if (!checkReply(reply)) {
460 throw new NetconfException("Request not successful with device "
461 + deviceInfo + " with reply " + reply);
462 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700463 return reply;
464 }
465
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200466
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700467 // FIXME rename to align with what it actually do
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200468 /**
469 * Validate and format netconf message.
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700470 * - NC1.0 if no EOM sequence present on {@code message}, append.
471 * - NC1.1 chunk-encode given message unless it already is chunk encoded
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200472 *
473 * @param message to format
474 * @return formated message
475 */
476 private String formatNetconfMessage(String message) {
477 if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) {
478 message = formatChunkedMessage(message);
479 } else {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700480 if (!message.endsWith(ENDPATTERN)) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200481 message = message + NEW_LINE + ENDPATTERN;
482 }
483 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700484 return message;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200485 }
486
487 /**
488 * Validate and format message according to chunked framing mechanism.
489 *
490 * @param message to format
491 * @return formated message
492 */
493 private String formatChunkedMessage(String message) {
494 if (message.endsWith(ENDPATTERN)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700495 // message given had Netconf 1.0 EOM pattern -> remove
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200496 message = message.substring(0, message.length() - ENDPATTERN.length());
497 }
498 if (!message.startsWith(LF + HASH)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700499 // chunk encode message
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700500 message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200501 }
502 return message;
503 }
504
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700505 @Override
506 @Deprecated
507 public CompletableFuture<String> request(String request) {
508 return streamHandler.sendMessage(request);
509 }
510
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700511 /**
512 * {@inheritDoc}
513 * <p>
514 * FIXME Note: as of 1.12.0
515 * {@code request} must not include message-id, this method will assign
516 * and insert message-id on it's own.
517 * Will require ONOS-7019 to remove this limitation.
518 */
519 @Override
520 public CompletableFuture<String> rpc(String request) {
521
522 String rpc = request;
523 // - assign message-id
524 int msgId = messageIdInteger.incrementAndGet();
525 // - re-write request to insert message-id
526 // FIXME avoid using formatRequestMessageId
527 rpc = formatRequestMessageId(rpc, msgId);
528 // - ensure it contains XML header
529 rpc = formatXmlHeader(rpc);
530 // - use chunked framing if talking to NC 1.1 device
531 // FIXME avoid using formatNetconfMessage
532 rpc = formatNetconfMessage(rpc);
533
534 // TODO session liveness check & recovery
535
536 log.debug("Sending {} to {}", rpc, this.deviceInfo.getDeviceId());
537 return streamHandler.sendMessage(rpc, msgId)
538 .handleAsync((reply, t) -> {
539 if (t != null) {
540 // secure transport-layer error
541 // cannot use NetconfException, which is
542 // checked Exception.
543 throw new NetconfTransportException(t);
544 } else {
545 // FIXME avoid using checkReply, error handling is weird
Kim JeongWoo8b03bc52018-08-10 16:50:23 +0900546 if (!checkReply(reply)) {
547 throw new NetconfTransportException("rpc-request not successful with device "
548 + deviceInfo + " with reply " + reply);
549 }
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700550 return reply;
551 }
552 }, SharedExecutors.getPoolThreadExecutor());
553 }
554
Sean Condon54d82432017-07-26 22:27:25 +0100555 @Override
556 public int timeoutConnectSec() {
557 return connectTimeout;
558 }
559
560 @Override
561 public int timeoutReplySec() {
562 return replyTimeout;
563 }
564
565 @Override
566 public int timeoutIdleSec() {
567 return idleTimeout;
568 }
569
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700570 private CompletableFuture<String> request(String request, int messageId) {
571 return streamHandler.sendMessage(request, messageId);
572 }
573
574 private String sendRequest(String request) throws NetconfException {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700575 // FIXME probably chunk-encoding too early
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200576 request = formatNetconfMessage(request);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700577 return sendRequest(request, false);
578 }
579
580 private String sendRequest(String request, boolean isHello) throws NetconfException {
581 checkAndReestablish();
582 int messageId = -1;
583 if (!isHello) {
584 messageId = messageIdInteger.getAndIncrement();
585 }
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700586 // FIXME potentially re-writing chunked encoded String?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700587 request = formatXmlHeader(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200588 request = formatRequestMessageId(request, messageId);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700589 log.debug("Sending request to NETCONF with timeout {} for {}",
590 replyTimeout, deviceInfo.name());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700591 CompletableFuture<String> futureReply = request(request, messageId);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700592 String rp;
593 try {
594 rp = futureReply.get(replyTimeout, TimeUnit.SECONDS);
Sean Condon7347de92017-07-21 12:17:25 +0100595 replies.remove(messageId); // Why here???
596 } catch (InterruptedException e) {
597 Thread.currentThread().interrupt();
598 throw new NetconfException("Interrupted waiting for reply for request" + request, e);
599 } catch (TimeoutException e) {
Sean Condon54d82432017-07-26 22:27:25 +0100600 throw new NetconfException("Timed out waiting for reply for request " +
601 request + " after " + replyTimeout + " sec.", e);
Sean Condon7347de92017-07-21 12:17:25 +0100602 } catch (ExecutionException e) {
603 log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e);
604 try {
605 session.close();
606 channel.close(); //Closes the socket which should interrupt NetconfStreamThread
607 client.close();
608 } catch (IOException ioe) {
609 log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe);
610 }
611 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
612 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
613 null, "Closed due to unexpected error " + e.getCause(),
614 Optional.of(-1), deviceInfo);
615 publishEvent(event);
616 errorReplies.clear(); // move to cleanUp()?
617 cleanUp();
618
619 throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo +
620 " for request " + request, e);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700621 }
622 log.debug("Result {} from request {} to device {}", rp, request, deviceInfo);
623 return rp.trim();
624 }
625
626 private String formatRequestMessageId(String request, int messageId) {
627 if (request.contains(MESSAGE_ID_STRING)) {
628 //FIXME if application provides his own counting of messages this fails that count
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700629 // FIXME assumes message-id is integer. RFC6241 allows anything as long as it is allowed in XML
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700630 request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200631 MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\"");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700632 } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) {
633 //FIXME find out a better way to enforce the presence of message-id
634 request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\""
635 + messageId + "\"" + ">");
636 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700637 request = updateRequestLength(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200638 return request;
639 }
640
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700641 private String updateRequestLength(String request) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200642 if (request.contains(LF + HASH + HASH + LF)) {
643 int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]);
644 String rpcWithEnding = request.substring(request.indexOf('<'));
645 String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0];
646 int newLen = 0;
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700647 newLen = firstBlock.getBytes(UTF_8).length;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200648 if (oldLen != newLen) {
649 return LF + HASH + newLen + LF + rpcWithEnding;
650 }
651 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700652 return request;
653 }
654
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700655 /**
656 * Ensures xml start directive/declaration appears in the {@code request}.
657 * @param request RPC request message
658 * @return XML RPC message
659 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700660 private String formatXmlHeader(String request) {
Sean Condon2d647172017-09-19 12:29:13 +0100661 if (!request.contains(XML_HEADER)) {
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700662 //FIXME if application provides his own XML header of different type there is a clash
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200663 if (request.startsWith(LF + HASH)) {
664 request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length());
665 } else {
666 request = XML_HEADER + "\n" + request;
667 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700668 }
669 return request;
670 }
671
672 @Override
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700673 public String getSessionId() {
674 return sessionID;
675 }
676
677 @Override
678 public Set<String> getDeviceCapabilitiesSet() {
679 return Collections.unmodifiableSet(deviceCapabilities);
680 }
681
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700682 @Override
683 public void setOnosCapabilities(Iterable<String> capabilities) {
684 onosCapabilities = capabilities;
685 }
686
687
688 @Override
689 public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
690 streamHandler.addDeviceEventListener(listener);
691 primaryListeners.add(listener);
692 }
693
694 @Override
695 public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
696 primaryListeners.remove(listener);
697 streamHandler.removeDeviceEventListener(listener);
698 }
699
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -0700700 @Override
701 protected boolean checkReply(String reply) {
702 // Overridden to record error logs
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700703 if (reply != null) {
704 if (!reply.contains("<rpc-error>")) {
705 log.debug("Device {} sent reply {}", deviceInfo, reply);
706 return true;
707 } else if (reply.contains("<ok/>")
708 || (reply.contains("<rpc-error>")
709 && reply.contains("warning"))) {
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700710 // FIXME rpc-error with a warning is considered same as Ok??
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700711 log.debug("Device {} sent reply {}", deviceInfo, reply);
712 return true;
713 }
714 }
715 log.warn("Device {} has error in reply {}", deviceInfo, reply);
716 return false;
717 }
718
zhongguo zhao78eab372018-08-27 16:22:39 +0800719 @Override
720 public boolean close() throws NetconfException {
721 try {
722 return super.close();
723 } catch (IOException ioe) {
724 throw new NetconfException(ioe.getMessage());
725 } finally {
726 try {
727 session.close();
728 channel.close();
729 client.close();
730 } catch (IOException ioe) {
731 log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe);
732 }
733 }
734 }
735
Sean Condon7347de92017-07-21 12:17:25 +0100736 protected void publishEvent(NetconfDeviceOutputEvent event) {
737 primaryListeners.forEach(lsnr -> {
738 if (lsnr.isRelevant(event)) {
739 lsnr.event(event);
740 }
741 });
742 }
743
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700744 static class NotificationSession extends NetconfSessionMinaImpl {
745
746 private String notificationFilter;
747
748 NotificationSession(NetconfDeviceInfo deviceInfo)
749 throws NetconfException {
750 super(deviceInfo);
751 }
752
753 @Override
754 protected void startSubscriptionStream(String filterSchema)
755 throws NetconfException {
756
757 notificationFilter = filterSchema;
758 requestSync(createSubscriptionString(filterSchema));
759 }
760
761 @Override
762 public String toString() {
763 return MoreObjects.toStringHelper(getClass())
764 .add("deviceInfo", deviceInfo)
765 .add("sessionID", getSessionId())
766 .add("notificationFilter", notificationFilter)
767 .toString();
768 }
769 }
770
771 /**
772 * Listener attached to child session for notification streaming.
773 * <p>
774 * Forwards all notification event from child session to primary session
775 * listeners.
776 */
777 private final class NotificationForwarder
778 implements NetconfDeviceOutputEventListener {
779
780 @Override
781 public boolean isRelevant(NetconfDeviceOutputEvent event) {
782 return event.type() == Type.DEVICE_NOTIFICATION;
783 }
784
785 @Override
786 public void event(NetconfDeviceOutputEvent event) {
Sean Condon7347de92017-07-21 12:17:25 +0100787 publishEvent(event);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700788 }
789 }
790
791 public class NetconfSessionDelegateImpl implements NetconfSessionDelegate {
792
793 @Override
794 public void notify(NetconfDeviceOutputEvent event) {
795 Optional<Integer> messageId = event.getMessageID();
796 log.debug("messageID {}, waiting replies messageIDs {}", messageId,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200797 replies.keySet());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700798 if (!messageId.isPresent()) {
799 errorReplies.add(event.getMessagePayload());
800 log.error("Device {} sent error reply {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200801 event.getDeviceInfo(), event.getMessagePayload());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700802 return;
803 }
804 CompletableFuture<String> completedReply =
Sean Condon7347de92017-07-21 12:17:25 +0100805 replies.get(messageId.get()); // remove(..)?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700806 if (completedReply != null) {
807 completedReply.complete(event.getMessagePayload());
808 }
809 }
810 }
811
Yuta HIGUCHI2ee4fba2018-06-12 16:21:06 -0700812 /**
813 * @deprecated in 1.14.0
814 */
815 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700816 public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory {
817
818 @Override
819 public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException {
820 return new NetconfSessionMinaImpl(netconfDeviceInfo);
821 }
822 }
Sean Condon54d82432017-07-26 22:27:25 +0100823}