blob: c7870b8b493103590ae8523c0bfa92a9225c83e8 [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
DongRyeol Chac29f9072018-11-06 14:05:56 +0900156 private boolean disconnected = false;
157
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700158 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
159 this.deviceInfo = deviceInfo;
160 replies = new ConcurrentHashMap<>();
161 errorReplies = new ArrayList<>();
quan PHAM VAN32d70e52018-08-01 17:35:30 -0700162 Set<String> capabilities = getClientCapabilites(deviceInfo.getDeviceId());
163 if (!capabilities.isEmpty()) {
164 capabilities.addAll(Sets.newHashSet(onosCapabilities));
165 setOnosCapabilities(capabilities);
166 }
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700167 // FIXME should not immediately start session on construction
168 // setOnosCapabilities() is useless due to this behavior
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700169 startConnection();
170 }
171
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200172 public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo, List<String> capabilities) throws NetconfException {
173 this.deviceInfo = deviceInfo;
174 replies = new ConcurrentHashMap<>();
175 errorReplies = new ArrayList<>();
176 setOnosCapabilities(capabilities);
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700177 // FIXME should not immediately start session on construction
178 // setOnosCapabilities() is useless due to this behavior
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200179 startConnection();
180 }
181
quan PHAM VAN32d70e52018-08-01 17:35:30 -0700182 /**
183 * Get the list of the netconf client capabilities from device driver property.
184 *
185 * @param deviceId the deviceID for which to recover the capabilities from the driver.
186 * @return the String list of clientCapability property, or null if it is not configured
187 */
188 public Set<String> getClientCapabilites(DeviceId deviceId) {
189 Set<String> capabilities = new LinkedHashSet<>();
190 DriverService driverService = directory.get(DriverService.class);
191 Driver driver = driverService.getDriver(deviceId);
192 if (driver == null) {
193 return capabilities;
194 }
195 String clientCapabilities = driver.getProperty(NETCONF_CLIENT_CAPABILITY);
196 if (clientCapabilities == null) {
197 return capabilities;
198 }
199 String[] textStr = clientCapabilities.split("\\|");
200 capabilities.addAll(Arrays.asList(textStr));
201 return capabilities;
202 }
203
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700204 private void startConnection() throws NetconfException {
Sean Condon54d82432017-07-26 22:27:25 +0100205 connectTimeout = deviceInfo.getConnectTimeoutSec().orElse(
206 NetconfControllerImpl.netconfConnectTimeout);
207 replyTimeout = deviceInfo.getReplyTimeoutSec().orElse(
208 NetconfControllerImpl.netconfReplyTimeout);
209 idleTimeout = deviceInfo.getIdleTimeoutSec().orElse(
210 NetconfControllerImpl.netconfIdleTimeout);
211 log.info("Connecting to {} with timeouts C:{}, R:{}, I:{}", deviceInfo,
212 connectTimeout, replyTimeout, idleTimeout);
213
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700214 try {
215 startClient();
DongRyeol Chac29f9072018-11-06 14:05:56 +0900216 } catch (Exception e) {
217 stopClient();
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700218 throw new NetconfException("Failed to establish SSH with device " + deviceInfo, e);
219 }
220 }
221
222 private void startClient() throws IOException {
Yuta HIGUCHI2ee4fba2018-06-12 16:21:06 -0700223 log.info("Creating NETCONF session to {}",
224 deviceInfo.getDeviceId());
225
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700226 client = SshClient.setUpDefaultClient();
Sean Condon7347de92017-07-21 12:17:25 +0100227 client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100228 TimeUnit.SECONDS.toMillis(idleTimeout));
Sean Condon7347de92017-07-21 12:17:25 +0100229 client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
Sean Condon54d82432017-07-26 22:27:25 +0100230 TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700231 client.start();
232 client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
233 startSession();
DongRyeol Chac29f9072018-11-06 14:05:56 +0900234
235 disconnected = false;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700236 }
237
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -0700238 //TODO: Remove the default methods already implemented in NetconfSession
239
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700240 // FIXME blocking
241 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700242 private void startSession() throws IOException {
243 final ConnectFuture connectFuture;
244 connectFuture = client.connect(deviceInfo.name(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200245 deviceInfo.ip().toString(),
246 deviceInfo.port())
Sean Condon54d82432017-07-26 22:27:25 +0100247 .verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700248 session = connectFuture.getSession();
249 //Using the device ssh key if possible
250 if (deviceInfo.getKey() != null) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700251 try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
252 JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
253 try {
254 KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
255 session.addPublicKeyIdentity(kp);
256 } catch (IOException e) {
257 throw new NetconfException("Failed to authenticate session with device " +
258 deviceInfo + "check key to be a valid key", e);
259 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700260 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700261 } else {
262 session.addPasswordIdentity(deviceInfo.password());
263 }
Sean Condon54d82432017-07-26 22:27:25 +0100264 session.auth().verify(connectTimeout, TimeUnit.SECONDS);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700265 Set<ClientSession.ClientSessionEvent> event = session.waitFor(
266 ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200267 ClientSession.ClientSessionEvent.CLOSED,
268 ClientSession.ClientSessionEvent.AUTHED), 0);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700269
270 if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
271 log.debug("Session closed {} {}", event, session.isClosed());
272 throw new NetconfException("Failed to authenticate session with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200273 deviceInfo + "check the user/pwd or key");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700274 }
275 openChannel();
276 }
277
278 private PublicKey getPublicKey(byte[] keyBytes, String type)
279 throws NoSuchAlgorithmException, InvalidKeySpecException {
280
281 X509EncodedKeySpec spec =
282 new X509EncodedKeySpec(keyBytes);
283 KeyFactory kf = KeyFactory.getInstance(type);
284 return kf.generatePublic(spec);
285 }
286
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700287 // FIXME blocking
288 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700289 private void openChannel() throws IOException {
290 channel = session.createSubsystemChannel("netconf");
291 OpenFuture channelFuture = channel.open();
Sean Condon54d82432017-07-26 22:27:25 +0100292 if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700293 if (channelFuture.isOpened()) {
294 streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(),
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200295 channel.getInvertedErr(), deviceInfo,
296 new NetconfSessionDelegateImpl(), replies);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700297 } else {
298 throw new NetconfException("Failed to open channel with device " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200299 deviceInfo);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700300 }
301 sendHello();
302 }
303 }
304
305
306 @Beta
307 protected void startSubscriptionStream(String filterSchema) throws NetconfException {
308 boolean openNewSession = false;
309 if (!deviceCapabilities.contains(INTERLEAVE_CAPABILITY_STRING)) {
310 log.info("Device {} doesn't support interleave, creating child session", deviceInfo);
311 openNewSession = true;
312
313 } else if (subscriptionConnected &&
314 notificationFilterSchema != null &&
315 !Objects.equal(filterSchema, notificationFilterSchema)) {
316 // interleave supported and existing filter is NOT "no filtering"
317 // and was requested with different filtering schema
318 log.info("Cannot use existing session for subscription {} ({})",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200319 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700320 openNewSession = true;
321 }
322
323 if (openNewSession) {
324 log.info("Creating notification session to {} with filter {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200325 deviceInfo, filterSchema);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700326 NetconfSession child = new NotificationSession(deviceInfo);
327
328 child.addDeviceOutputListener(new NotificationForwarder());
329
330 child.startSubscription(filterSchema);
331 children.add(child);
332 return;
333 }
334
335 // request to start interleaved notification session
336 String reply = sendRequest(createSubscriptionString(filterSchema));
337 if (!checkReply(reply)) {
338 throw new NetconfException("Subscription not successful with device "
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200339 + deviceInfo + " with reply " + reply);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700340 }
341 subscriptionConnected = true;
342 }
343
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700344 @Beta
345 @Override
346 public void startSubscription(String filterSchema) throws NetconfException {
347 if (!subscriptionConnected) {
348 notificationFilterSchema = filterSchema;
349 startSubscriptionStream(filterSchema);
350 }
351 streamHandler.setEnableNotifications(true);
352 }
353
354 @Beta
355 protected String createSubscriptionString(String filterSchema) {
356 StringBuilder subscriptionbuffer = new StringBuilder();
357 subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
358 subscriptionbuffer.append(" <create-subscription\n");
359 subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n");
Laszlo Pappbdb64082018-09-11 12:21:29 +0100360 DriverService driverService = directory.get(DriverService.class);
361 Driver driver = driverService.getDriver(deviceInfo.getDeviceId());
362 if (driver != null) {
363 String stream = driver.getProperty(NOTIFICATION_STREAM);
364 if (stream != null) {
365 subscriptionbuffer.append(" <stream>");
366 subscriptionbuffer.append(stream);
367 subscriptionbuffer.append("</stream>\n");
368 }
369 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700370 // FIXME Only subtree filtering supported at the moment.
371 if (filterSchema != null) {
372 subscriptionbuffer.append(" ");
373 subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE);
374 subscriptionbuffer.append(filterSchema).append(NEW_LINE);
375 subscriptionbuffer.append(" ");
376 subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
377 }
378 subscriptionbuffer.append(" </create-subscription>\n");
379 subscriptionbuffer.append("</rpc>\n");
380 subscriptionbuffer.append(ENDPATTERN);
381 return subscriptionbuffer.toString();
382 }
383
384 @Override
385 public void endSubscription() throws NetconfException {
386 if (subscriptionConnected) {
387 streamHandler.setEnableNotifications(false);
388 } else {
389 throw new NetconfException("Subscription does not exist.");
390 }
391 }
392
DongRyeol Chac29f9072018-11-06 14:05:56 +0900393 private void stopClient() {
394 if (session != null) {
395 try {
396 session.close();
397 } catch (IOException ex) {
398 log.warn("Cannot close session {} {}", sessionID, deviceInfo, ex);
399 }
400 }
401
402 if (channel != null) {
403 try {
404 channel.close();
405 } catch (IOException ex) {
406 log.warn("Cannot close channel {} {}", sessionID, deviceInfo, ex);
407 }
408 }
409
410 if (client != null) {
411 try {
412 client.close();
413 } catch (IOException ex) {
414 log.warn("Cannot close client {} {}", sessionID, deviceInfo, ex);
415 }
416
417 client.stop();
418 }
419 }
420
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700421 private void sendHello() throws NetconfException {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700422 String serverHelloResponse = sendRequest(createHelloString(), true);
423 Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700424 while (capabilityMatcher.find()) {
425 deviceCapabilities.add(capabilityMatcher.group(1));
426 }
427 sessionID = String.valueOf(-1);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700428 Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700429 if (sessionIDMatcher.find()) {
430 sessionID = sessionIDMatcher.group(1);
431 } else {
432 throw new NetconfException("Missing SessionID in server hello " +
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200433 "reponse.");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700434 }
435
436 }
437
438 private String createHelloString() {
439 StringBuilder hellobuffer = new StringBuilder();
440 hellobuffer.append(XML_HEADER);
441 hellobuffer.append("\n");
442 hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
443 hellobuffer.append(" <capabilities>\n");
444 onosCapabilities.forEach(
445 cap -> hellobuffer.append(" <capability>")
446 .append(cap)
447 .append("</capability>\n"));
448 hellobuffer.append(" </capabilities>\n");
449 hellobuffer.append("</hello>\n");
450 hellobuffer.append(ENDPATTERN);
451 return hellobuffer.toString();
452
453 }
454
455 @Override
456 public void checkAndReestablish() throws NetconfException {
DongRyeol Chac29f9072018-11-06 14:05:56 +0900457 if (disconnected) {
458 log.warn("Can't reopen connection for device because of disconnected {}", deviceInfo.getDeviceId());
459 throw new NetconfException("Can't reopen connection for device because of disconnected " + deviceInfo);
460 }
461
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700462 try {
zhongguo zhao98bb37a2018-08-28 16:17:06 +0800463 if (client.isClosed() || client.isClosing()) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700464 log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId());
465 cleanUp();
466 startConnection();
zhongguo zhao98bb37a2018-08-28 16:17:06 +0800467 } else if (session.isClosed() || session.isClosing()) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700468 log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId());
469 cleanUp();
470 startSession();
zhongguo zhao98bb37a2018-08-28 16:17:06 +0800471 } else if (channel.isClosed() || channel.isClosing()) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700472 log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId());
473 cleanUp();
474 openChannel();
Andrea Campanella856f3132017-10-23 15:46:36 +0200475 } else {
476 return;
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700477 }
478 if (subscriptionConnected) {
479 log.debug("Restarting subscription with {}", deviceInfo.getDeviceId());
480 subscriptionConnected = false;
481 startSubscription(notificationFilterSchema);
482 }
Sean Condon7347de92017-07-21 12:17:25 +0100483 } catch (IOException | IllegalStateException e) {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700484 log.error("Can't reopen connection for device {}", e.getMessage());
485 throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e);
486 }
487 }
488
489 private void cleanUp() {
490 //makes sure everything is at a clean state.
491 replies.clear();
492 }
493
494 @Override
495 public String requestSync(String request) throws NetconfException {
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700496 String reply = sendRequest(request);
Kim JeongWoo8b03bc52018-08-10 16:50:23 +0900497 if (!checkReply(reply)) {
498 throw new NetconfException("Request not successful with device "
499 + deviceInfo + " with reply " + reply);
500 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700501 return reply;
502 }
503
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200504
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700505 // FIXME rename to align with what it actually do
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200506 /**
507 * Validate and format netconf message.
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700508 * - NC1.0 if no EOM sequence present on {@code message}, append.
509 * - NC1.1 chunk-encode given message unless it already is chunk encoded
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200510 *
511 * @param message to format
512 * @return formated message
513 */
514 private String formatNetconfMessage(String message) {
515 if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) {
516 message = formatChunkedMessage(message);
517 } else {
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700518 if (!message.endsWith(ENDPATTERN)) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200519 message = message + NEW_LINE + ENDPATTERN;
520 }
521 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700522 return message;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200523 }
524
525 /**
526 * Validate and format message according to chunked framing mechanism.
527 *
528 * @param message to format
529 * @return formated message
530 */
531 private String formatChunkedMessage(String message) {
532 if (message.endsWith(ENDPATTERN)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700533 // message given had Netconf 1.0 EOM pattern -> remove
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200534 message = message.substring(0, message.length() - ENDPATTERN.length());
535 }
536 if (!message.startsWith(LF + HASH)) {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700537 // chunk encode message
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700538 message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200539 }
540 return message;
541 }
542
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700543 @Override
544 @Deprecated
545 public CompletableFuture<String> request(String request) {
546 return streamHandler.sendMessage(request);
547 }
548
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700549 /**
550 * {@inheritDoc}
551 * <p>
552 * FIXME Note: as of 1.12.0
553 * {@code request} must not include message-id, this method will assign
554 * and insert message-id on it's own.
555 * Will require ONOS-7019 to remove this limitation.
556 */
557 @Override
558 public CompletableFuture<String> rpc(String request) {
559
560 String rpc = request;
561 // - assign message-id
562 int msgId = messageIdInteger.incrementAndGet();
563 // - re-write request to insert message-id
564 // FIXME avoid using formatRequestMessageId
565 rpc = formatRequestMessageId(rpc, msgId);
566 // - ensure it contains XML header
567 rpc = formatXmlHeader(rpc);
568 // - use chunked framing if talking to NC 1.1 device
569 // FIXME avoid using formatNetconfMessage
570 rpc = formatNetconfMessage(rpc);
571
572 // TODO session liveness check & recovery
573
574 log.debug("Sending {} to {}", rpc, this.deviceInfo.getDeviceId());
575 return streamHandler.sendMessage(rpc, msgId)
576 .handleAsync((reply, t) -> {
577 if (t != null) {
578 // secure transport-layer error
579 // cannot use NetconfException, which is
580 // checked Exception.
581 throw new NetconfTransportException(t);
582 } else {
583 // FIXME avoid using checkReply, error handling is weird
Kim JeongWoo8b03bc52018-08-10 16:50:23 +0900584 if (!checkReply(reply)) {
585 throw new NetconfTransportException("rpc-request not successful with device "
586 + deviceInfo + " with reply " + reply);
587 }
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700588 return reply;
589 }
590 }, SharedExecutors.getPoolThreadExecutor());
591 }
592
Sean Condon54d82432017-07-26 22:27:25 +0100593 @Override
594 public int timeoutConnectSec() {
595 return connectTimeout;
596 }
597
598 @Override
599 public int timeoutReplySec() {
600 return replyTimeout;
601 }
602
603 @Override
604 public int timeoutIdleSec() {
605 return idleTimeout;
606 }
607
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700608 private CompletableFuture<String> request(String request, int messageId) {
609 return streamHandler.sendMessage(request, messageId);
610 }
611
612 private String sendRequest(String request) throws NetconfException {
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700613 // FIXME probably chunk-encoding too early
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200614 request = formatNetconfMessage(request);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700615 return sendRequest(request, false);
616 }
617
618 private String sendRequest(String request, boolean isHello) throws NetconfException {
619 checkAndReestablish();
620 int messageId = -1;
621 if (!isHello) {
622 messageId = messageIdInteger.getAndIncrement();
623 }
Yuta HIGUCHIb2d05242017-09-05 15:44:34 -0700624 // FIXME potentially re-writing chunked encoded String?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700625 request = formatXmlHeader(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200626 request = formatRequestMessageId(request, messageId);
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700627 log.debug("Sending request to NETCONF with timeout {} for {}",
628 replyTimeout, deviceInfo.name());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700629 CompletableFuture<String> futureReply = request(request, messageId);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700630 String rp;
631 try {
632 rp = futureReply.get(replyTimeout, TimeUnit.SECONDS);
Sean Condon7347de92017-07-21 12:17:25 +0100633 replies.remove(messageId); // Why here???
634 } catch (InterruptedException e) {
635 Thread.currentThread().interrupt();
636 throw new NetconfException("Interrupted waiting for reply for request" + request, e);
637 } catch (TimeoutException e) {
Sean Condon54d82432017-07-26 22:27:25 +0100638 throw new NetconfException("Timed out waiting for reply for request " +
639 request + " after " + replyTimeout + " sec.", e);
Sean Condon7347de92017-07-21 12:17:25 +0100640 } catch (ExecutionException e) {
641 log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e);
DongRyeol Chac29f9072018-11-06 14:05:56 +0900642 stopClient();
Sean Condon7347de92017-07-21 12:17:25 +0100643 NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
644 NetconfDeviceOutputEvent.Type.SESSION_CLOSED,
645 null, "Closed due to unexpected error " + e.getCause(),
646 Optional.of(-1), deviceInfo);
647 publishEvent(event);
648 errorReplies.clear(); // move to cleanUp()?
649 cleanUp();
650
651 throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo +
652 " for request " + request, e);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700653 }
654 log.debug("Result {} from request {} to device {}", rp, request, deviceInfo);
655 return rp.trim();
656 }
657
658 private String formatRequestMessageId(String request, int messageId) {
659 if (request.contains(MESSAGE_ID_STRING)) {
660 //FIXME if application provides his own counting of messages this fails that count
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700661 // FIXME assumes message-id is integer. RFC6241 allows anything as long as it is allowed in XML
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700662 request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200663 MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\"");
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700664 } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) {
665 //FIXME find out a better way to enforce the presence of message-id
666 request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\""
667 + messageId + "\"" + ">");
668 }
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700669 request = updateRequestLength(request);
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200670 return request;
671 }
672
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700673 private String updateRequestLength(String request) {
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200674 if (request.contains(LF + HASH + HASH + LF)) {
675 int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]);
676 String rpcWithEnding = request.substring(request.indexOf('<'));
677 String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0];
678 int newLen = 0;
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700679 newLen = firstBlock.getBytes(UTF_8).length;
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200680 if (oldLen != newLen) {
681 return LF + HASH + newLen + LF + rpcWithEnding;
682 }
683 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700684 return request;
685 }
686
Yuta HIGUCHI371667d2017-09-05 17:30:51 -0700687 /**
688 * Ensures xml start directive/declaration appears in the {@code request}.
689 * @param request RPC request message
690 * @return XML RPC message
691 */
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700692 private String formatXmlHeader(String request) {
Sean Condon2d647172017-09-19 12:29:13 +0100693 if (!request.contains(XML_HEADER)) {
Yuta HIGUCHI15677982017-08-16 15:50:29 -0700694 //FIXME if application provides his own XML header of different type there is a clash
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200695 if (request.startsWith(LF + HASH)) {
696 request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length());
697 } else {
698 request = XML_HEADER + "\n" + request;
699 }
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700700 }
701 return request;
702 }
703
704 @Override
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700705 public String getSessionId() {
706 return sessionID;
707 }
708
709 @Override
710 public Set<String> getDeviceCapabilitiesSet() {
711 return Collections.unmodifiableSet(deviceCapabilities);
712 }
713
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700714 @Override
715 public void setOnosCapabilities(Iterable<String> capabilities) {
716 onosCapabilities = capabilities;
717 }
718
719
720 @Override
721 public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
722 streamHandler.addDeviceEventListener(listener);
723 primaryListeners.add(listener);
724 }
725
726 @Override
727 public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
728 primaryListeners.remove(listener);
729 streamHandler.removeDeviceEventListener(listener);
730 }
731
Yuta HIGUCHI4f55c672018-06-14 18:10:43 -0700732 @Override
733 protected boolean checkReply(String reply) {
734 // Overridden to record error logs
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700735 if (reply != null) {
736 if (!reply.contains("<rpc-error>")) {
737 log.debug("Device {} sent reply {}", deviceInfo, reply);
738 return true;
739 } else if (reply.contains("<ok/>")
740 || (reply.contains("<rpc-error>")
741 && reply.contains("warning"))) {
Yuta HIGUCHI6e6c26e2017-09-06 14:25:57 -0700742 // FIXME rpc-error with a warning is considered same as Ok??
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700743 log.debug("Device {} sent reply {}", deviceInfo, reply);
744 return true;
745 }
746 }
747 log.warn("Device {} has error in reply {}", deviceInfo, reply);
748 return false;
749 }
750
zhongguo zhao78eab372018-08-27 16:22:39 +0800751 @Override
752 public boolean close() throws NetconfException {
753 try {
DongRyeol Chac29f9072018-11-06 14:05:56 +0900754 if (client != null && (client.isClosed() || client.isClosing())) {
755 return true;
756 }
757
zhongguo zhao78eab372018-08-27 16:22:39 +0800758 return super.close();
759 } catch (IOException ioe) {
760 throw new NetconfException(ioe.getMessage());
761 } finally {
DongRyeol Chac29f9072018-11-06 14:05:56 +0900762 disconnected = true;
763 stopClient();
zhongguo zhao78eab372018-08-27 16:22:39 +0800764 }
765 }
766
Sean Condon7347de92017-07-21 12:17:25 +0100767 protected void publishEvent(NetconfDeviceOutputEvent event) {
768 primaryListeners.forEach(lsnr -> {
769 if (lsnr.isRelevant(event)) {
770 lsnr.event(event);
771 }
772 });
773 }
774
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700775 static class NotificationSession extends NetconfSessionMinaImpl {
776
777 private String notificationFilter;
778
779 NotificationSession(NetconfDeviceInfo deviceInfo)
780 throws NetconfException {
781 super(deviceInfo);
782 }
783
784 @Override
785 protected void startSubscriptionStream(String filterSchema)
786 throws NetconfException {
787
788 notificationFilter = filterSchema;
789 requestSync(createSubscriptionString(filterSchema));
790 }
791
792 @Override
793 public String toString() {
794 return MoreObjects.toStringHelper(getClass())
795 .add("deviceInfo", deviceInfo)
796 .add("sessionID", getSessionId())
797 .add("notificationFilter", notificationFilter)
798 .toString();
799 }
800 }
801
802 /**
803 * Listener attached to child session for notification streaming.
804 * <p>
805 * Forwards all notification event from child session to primary session
806 * listeners.
807 */
808 private final class NotificationForwarder
809 implements NetconfDeviceOutputEventListener {
810
811 @Override
812 public boolean isRelevant(NetconfDeviceOutputEvent event) {
813 return event.type() == Type.DEVICE_NOTIFICATION;
814 }
815
816 @Override
817 public void event(NetconfDeviceOutputEvent event) {
Sean Condon7347de92017-07-21 12:17:25 +0100818 publishEvent(event);
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700819 }
820 }
821
822 public class NetconfSessionDelegateImpl implements NetconfSessionDelegate {
823
824 @Override
825 public void notify(NetconfDeviceOutputEvent event) {
826 Optional<Integer> messageId = event.getMessageID();
827 log.debug("messageID {}, waiting replies messageIDs {}", messageId,
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200828 replies.keySet());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700829 if (!messageId.isPresent()) {
830 errorReplies.add(event.getMessagePayload());
831 log.error("Device {} sent error reply {}",
Kamil Stasiak9f59f442017-05-02 11:02:24 +0200832 event.getDeviceInfo(), event.getMessagePayload());
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700833 return;
834 }
835 CompletableFuture<String> completedReply =
Sean Condon7347de92017-07-21 12:17:25 +0100836 replies.get(messageId.get()); // remove(..)?
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700837 if (completedReply != null) {
838 completedReply.complete(event.getMessagePayload());
839 }
840 }
841 }
842
Yuta HIGUCHI2ee4fba2018-06-12 16:21:06 -0700843 /**
844 * @deprecated in 1.14.0
845 */
846 @Deprecated
Andrea Campanella7bbe7b12017-05-03 16:03:38 -0700847 public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory {
848
849 @Override
850 public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException {
851 return new NetconfSessionMinaImpl(netconfDeviceInfo);
852 }
853 }
Sean Condon54d82432017-07-26 22:27:25 +0100854}