Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2015-present Open Networking Foundation |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 3 | * |
| 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 | |
| 17 | package org.onosproject.netconf.ctl.impl; |
| 18 | |
| 19 | import com.google.common.annotations.Beta; |
| 20 | import com.google.common.base.MoreObjects; |
| 21 | import com.google.common.base.Objects; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 22 | import com.google.common.collect.ImmutableList; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 23 | import com.google.common.collect.ImmutableSet; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 24 | import com.google.common.collect.Sets; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 25 | import org.apache.sshd.client.SshClient; |
| 26 | import org.apache.sshd.client.channel.ClientChannel; |
| 27 | import org.apache.sshd.client.future.ConnectFuture; |
| 28 | import org.apache.sshd.client.future.OpenFuture; |
| 29 | import org.apache.sshd.client.session.ClientSession; |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 30 | import org.apache.sshd.common.FactoryManager; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 31 | import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; |
Holger Schulz | 092cbbf | 2017-08-31 17:52:30 +0200 | [diff] [blame] | 32 | import org.bouncycastle.jce.provider.BouncyCastleProvider; |
Holger Schulz | 092cbbf | 2017-08-31 17:52:30 +0200 | [diff] [blame] | 33 | import org.bouncycastle.openssl.PEMKeyPair; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 34 | import org.bouncycastle.openssl.PEMParser; |
Holger Schulz | 092cbbf | 2017-08-31 17:52:30 +0200 | [diff] [blame] | 35 | import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 36 | import org.onlab.osgi.DefaultServiceDirectory; |
| 37 | import org.onlab.osgi.ServiceDirectory; |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 38 | import org.onlab.util.SharedExecutors; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 39 | import org.onosproject.net.DeviceId; |
| 40 | import org.onosproject.net.driver.Driver; |
| 41 | import org.onosproject.net.driver.DriverService; |
Yuta HIGUCHI | 4f55c67 | 2018-06-14 18:10:43 -0700 | [diff] [blame] | 42 | import org.onosproject.netconf.AbstractNetconfSession; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 43 | import org.onosproject.netconf.NetconfDeviceInfo; |
| 44 | import org.onosproject.netconf.NetconfDeviceOutputEvent; |
| 45 | import org.onosproject.netconf.NetconfDeviceOutputEvent.Type; |
| 46 | import org.onosproject.netconf.NetconfDeviceOutputEventListener; |
| 47 | import org.onosproject.netconf.NetconfException; |
| 48 | import org.onosproject.netconf.NetconfSession; |
| 49 | import org.onosproject.netconf.NetconfSessionFactory; |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 50 | import org.onosproject.netconf.NetconfTransportException; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 51 | import org.slf4j.Logger; |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 52 | |
Holger Schulz | 092cbbf | 2017-08-31 17:52:30 +0200 | [diff] [blame] | 53 | import java.io.CharArrayReader; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 54 | import java.io.IOException; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 55 | import java.security.KeyFactory; |
| 56 | import java.security.KeyPair; |
| 57 | import java.security.NoSuchAlgorithmException; |
| 58 | import java.security.PublicKey; |
| 59 | import java.security.spec.InvalidKeySpecException; |
| 60 | import java.security.spec.X509EncodedKeySpec; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 61 | import java.util.ArrayList; |
| 62 | import java.util.Arrays; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 63 | import java.util.Collection; |
| 64 | import java.util.Collections; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 65 | import java.util.LinkedHashSet; |
| 66 | import java.util.List; |
| 67 | import java.util.Map; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 68 | import java.util.Optional; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 69 | import java.util.Set; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 70 | import java.util.concurrent.CompletableFuture; |
| 71 | import java.util.concurrent.ConcurrentHashMap; |
| 72 | import java.util.concurrent.CopyOnWriteArrayList; |
| 73 | import java.util.concurrent.ExecutionException; |
| 74 | import java.util.concurrent.TimeUnit; |
| 75 | import java.util.concurrent.TimeoutException; |
| 76 | import java.util.concurrent.atomic.AtomicInteger; |
| 77 | import java.util.regex.Matcher; |
| 78 | import java.util.regex.Pattern; |
| 79 | |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 80 | import static java.nio.charset.StandardCharsets.UTF_8; |
| 81 | import static org.slf4j.LoggerFactory.getLogger; |
| 82 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 83 | /** |
| 84 | * Implementation of a NETCONF session to talk to a device. |
| 85 | */ |
Yuta HIGUCHI | 4f55c67 | 2018-06-14 18:10:43 -0700 | [diff] [blame] | 86 | public class NetconfSessionMinaImpl extends AbstractNetconfSession { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 87 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 88 | private static final Logger log = getLogger(NetconfSessionMinaImpl.class); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 89 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 90 | /** |
| 91 | * NC 1.0, RFC4742 EOM sequence. |
| 92 | */ |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 93 | 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 100 | private static final String SUBTREE_FILTER_CLOSE = "</filter>"; |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 101 | // FIXME hard coded namespace nc |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 102 | private static final String XML_HEADER = |
| 103 | "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; |
Yuta HIGUCHI | 4f55c67 | 2018-06-14 18:10:43 -0700 | [diff] [blame] | 104 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 105 | // FIXME hard coded namespace base10 |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 106 | 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 Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 116 | 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 VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 121 | private static final String NETCONF_CLIENT_CAPABILITY = "netconfClientCapability"; |
Laszlo Papp | bdb6408 | 2018-09-11 12:21:29 +0100 | [diff] [blame^] | 122 | private static final String NOTIFICATION_STREAM = "notificationStream"; |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 123 | |
| 124 | private static ServiceDirectory directory = new DefaultServiceDirectory(); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 125 | |
| 126 | private String sessionID; |
| 127 | private final AtomicInteger messageIdInteger = new AtomicInteger(1); |
| 128 | protected final NetconfDeviceInfo deviceInfo; |
| 129 | private Iterable<String> onosCapabilities = |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 130 | ImmutableList.of(NETCONF_10_CAPABILITY, NETCONF_11_CAPABILITY); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 131 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 132 | private final Set<String> deviceCapabilities = new LinkedHashSet<>(); |
| 133 | private NetconfStreamHandler streamHandler; |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 134 | // 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 138 | private Map<Integer, CompletableFuture<String>> replies; |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 139 | private List<String> errorReplies; // Not sure why we need this? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 140 | 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 Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 148 | private int connectTimeout; |
| 149 | private int replyTimeout; |
| 150 | private int idleTimeout; |
| 151 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 152 | private ClientChannel channel = null; |
| 153 | private ClientSession session = null; |
| 154 | private SshClient client = null; |
| 155 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 156 | public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException { |
| 157 | this.deviceInfo = deviceInfo; |
| 158 | replies = new ConcurrentHashMap<>(); |
| 159 | errorReplies = new ArrayList<>(); |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 160 | Set<String> capabilities = getClientCapabilites(deviceInfo.getDeviceId()); |
| 161 | if (!capabilities.isEmpty()) { |
| 162 | capabilities.addAll(Sets.newHashSet(onosCapabilities)); |
| 163 | setOnosCapabilities(capabilities); |
| 164 | } |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 165 | // FIXME should not immediately start session on construction |
| 166 | // setOnosCapabilities() is useless due to this behavior |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 167 | startConnection(); |
| 168 | } |
| 169 | |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 170 | 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 HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 175 | // FIXME should not immediately start session on construction |
| 176 | // setOnosCapabilities() is useless due to this behavior |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 177 | startConnection(); |
| 178 | } |
| 179 | |
quan PHAM VAN | 32d70e5 | 2018-08-01 17:35:30 -0700 | [diff] [blame] | 180 | /** |
| 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 202 | private void startConnection() throws NetconfException { |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 203 | 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 212 | 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 HIGUCHI | 2ee4fba | 2018-06-12 16:21:06 -0700 | [diff] [blame] | 220 | log.info("Creating NETCONF session to {}", |
| 221 | deviceInfo.getDeviceId()); |
| 222 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 223 | client = SshClient.setUpDefaultClient(); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 224 | client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT, |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 225 | TimeUnit.SECONDS.toMillis(idleTimeout)); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 226 | client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 227 | TimeUnit.SECONDS.toMillis(idleTimeout + 15L)); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 228 | client.start(); |
| 229 | client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider()); |
| 230 | startSession(); |
| 231 | } |
| 232 | |
Yuta HIGUCHI | 4f55c67 | 2018-06-14 18:10:43 -0700 | [diff] [blame] | 233 | //TODO: Remove the default methods already implemented in NetconfSession |
| 234 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 235 | // FIXME blocking |
| 236 | @Deprecated |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 237 | private void startSession() throws IOException { |
| 238 | final ConnectFuture connectFuture; |
| 239 | connectFuture = client.connect(deviceInfo.name(), |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 240 | deviceInfo.ip().toString(), |
| 241 | deviceInfo.port()) |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 242 | .verify(connectTimeout, TimeUnit.SECONDS); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 243 | session = connectFuture.getSession(); |
| 244 | //Using the device ssh key if possible |
| 245 | if (deviceInfo.getKey() != null) { |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 246 | 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 255 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 256 | } else { |
| 257 | session.addPasswordIdentity(deviceInfo.password()); |
| 258 | } |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 259 | session.auth().verify(connectTimeout, TimeUnit.SECONDS); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 260 | Set<ClientSession.ClientSessionEvent> event = session.waitFor( |
| 261 | ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 262 | ClientSession.ClientSessionEvent.CLOSED, |
| 263 | ClientSession.ClientSessionEvent.AUTHED), 0); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 264 | |
| 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 Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 268 | deviceInfo + "check the user/pwd or key"); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 269 | } |
| 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 HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 282 | // FIXME blocking |
| 283 | @Deprecated |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 284 | private void openChannel() throws IOException { |
| 285 | channel = session.createSubsystemChannel("netconf"); |
| 286 | OpenFuture channelFuture = channel.open(); |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 287 | if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 288 | if (channelFuture.isOpened()) { |
| 289 | streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(), |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 290 | channel.getInvertedErr(), deviceInfo, |
| 291 | new NetconfSessionDelegateImpl(), replies); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 292 | } else { |
| 293 | throw new NetconfException("Failed to open channel with device " + |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 294 | deviceInfo); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 295 | } |
| 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 Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 314 | deviceInfo, filterSchema); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 315 | openNewSession = true; |
| 316 | } |
| 317 | |
| 318 | if (openNewSession) { |
| 319 | log.info("Creating notification session to {} with filter {}", |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 320 | deviceInfo, filterSchema); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 321 | 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 Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 334 | + deviceInfo + " with reply " + reply); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 335 | } |
| 336 | subscriptionConnected = true; |
| 337 | } |
| 338 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 339 | @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 Papp | bdb6408 | 2018-09-11 12:21:29 +0100 | [diff] [blame^] | 355 | 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 365 | // 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 HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 389 | String serverHelloResponse = sendRequest(createHelloString(), true); |
| 390 | Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 391 | while (capabilityMatcher.find()) { |
| 392 | deviceCapabilities.add(capabilityMatcher.group(1)); |
| 393 | } |
| 394 | sessionID = String.valueOf(-1); |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 395 | Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 396 | if (sessionIDMatcher.find()) { |
| 397 | sessionID = sessionIDMatcher.group(1); |
| 398 | } else { |
| 399 | throw new NetconfException("Missing SessionID in server hello " + |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 400 | "reponse."); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 401 | } |
| 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 zhao | 98bb37a | 2018-08-28 16:17:06 +0800 | [diff] [blame] | 425 | if (client.isClosed() || client.isClosing()) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 426 | log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId()); |
| 427 | cleanUp(); |
| 428 | startConnection(); |
zhongguo zhao | 98bb37a | 2018-08-28 16:17:06 +0800 | [diff] [blame] | 429 | } else if (session.isClosed() || session.isClosing()) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 430 | log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId()); |
| 431 | cleanUp(); |
| 432 | startSession(); |
zhongguo zhao | 98bb37a | 2018-08-28 16:17:06 +0800 | [diff] [blame] | 433 | } else if (channel.isClosed() || channel.isClosing()) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 434 | log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId()); |
| 435 | cleanUp(); |
| 436 | openChannel(); |
Andrea Campanella | 856f313 | 2017-10-23 15:46:36 +0200 | [diff] [blame] | 437 | } else { |
| 438 | return; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 439 | } |
| 440 | if (subscriptionConnected) { |
| 441 | log.debug("Restarting subscription with {}", deviceInfo.getDeviceId()); |
| 442 | subscriptionConnected = false; |
| 443 | startSubscription(notificationFilterSchema); |
| 444 | } |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 445 | } catch (IOException | IllegalStateException e) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 446 | 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 458 | String reply = sendRequest(request); |
Kim JeongWoo | 8b03bc5 | 2018-08-10 16:50:23 +0900 | [diff] [blame] | 459 | if (!checkReply(reply)) { |
| 460 | throw new NetconfException("Request not successful with device " |
| 461 | + deviceInfo + " with reply " + reply); |
| 462 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 463 | return reply; |
| 464 | } |
| 465 | |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 466 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 467 | // FIXME rename to align with what it actually do |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 468 | /** |
| 469 | * Validate and format netconf message. |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 470 | * - 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 Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 472 | * |
| 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 HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 480 | if (!message.endsWith(ENDPATTERN)) { |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 481 | message = message + NEW_LINE + ENDPATTERN; |
| 482 | } |
| 483 | } |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 484 | return message; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 485 | } |
| 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 HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 495 | // message given had Netconf 1.0 EOM pattern -> remove |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 496 | message = message.substring(0, message.length() - ENDPATTERN.length()); |
| 497 | } |
| 498 | if (!message.startsWith(LF + HASH)) { |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 499 | // chunk encode message |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 500 | message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 501 | } |
| 502 | return message; |
| 503 | } |
| 504 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 505 | @Override |
| 506 | @Deprecated |
| 507 | public CompletableFuture<String> request(String request) { |
| 508 | return streamHandler.sendMessage(request); |
| 509 | } |
| 510 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 511 | /** |
| 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 JeongWoo | 8b03bc5 | 2018-08-10 16:50:23 +0900 | [diff] [blame] | 546 | if (!checkReply(reply)) { |
| 547 | throw new NetconfTransportException("rpc-request not successful with device " |
| 548 | + deviceInfo + " with reply " + reply); |
| 549 | } |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 550 | return reply; |
| 551 | } |
| 552 | }, SharedExecutors.getPoolThreadExecutor()); |
| 553 | } |
| 554 | |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 555 | @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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 570 | 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 HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 575 | // FIXME probably chunk-encoding too early |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 576 | request = formatNetconfMessage(request); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 577 | 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 HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 586 | // FIXME potentially re-writing chunked encoded String? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 587 | request = formatXmlHeader(request); |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 588 | request = formatRequestMessageId(request, messageId); |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 589 | log.debug("Sending request to NETCONF with timeout {} for {}", |
| 590 | replyTimeout, deviceInfo.name()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 591 | CompletableFuture<String> futureReply = request(request, messageId); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 592 | String rp; |
| 593 | try { |
| 594 | rp = futureReply.get(replyTimeout, TimeUnit.SECONDS); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 595 | 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 Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 600 | throw new NetconfException("Timed out waiting for reply for request " + |
| 601 | request + " after " + replyTimeout + " sec.", e); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 602 | } 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 621 | } |
| 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 HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 629 | // FIXME assumes message-id is integer. RFC6241 allows anything as long as it is allowed in XML |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 630 | request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER, |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 631 | MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\""); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 632 | } 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 HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 637 | request = updateRequestLength(request); |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 638 | return request; |
| 639 | } |
| 640 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 641 | private String updateRequestLength(String request) { |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 642 | 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 HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 647 | newLen = firstBlock.getBytes(UTF_8).length; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 648 | if (oldLen != newLen) { |
| 649 | return LF + HASH + newLen + LF + rpcWithEnding; |
| 650 | } |
| 651 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 652 | return request; |
| 653 | } |
| 654 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 655 | /** |
| 656 | * Ensures xml start directive/declaration appears in the {@code request}. |
| 657 | * @param request RPC request message |
| 658 | * @return XML RPC message |
| 659 | */ |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 660 | private String formatXmlHeader(String request) { |
Sean Condon | 2d64717 | 2017-09-19 12:29:13 +0100 | [diff] [blame] | 661 | if (!request.contains(XML_HEADER)) { |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 662 | //FIXME if application provides his own XML header of different type there is a clash |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 663 | 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 Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 668 | } |
| 669 | return request; |
| 670 | } |
| 671 | |
| 672 | @Override |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 673 | public String getSessionId() { |
| 674 | return sessionID; |
| 675 | } |
| 676 | |
| 677 | @Override |
| 678 | public Set<String> getDeviceCapabilitiesSet() { |
| 679 | return Collections.unmodifiableSet(deviceCapabilities); |
| 680 | } |
| 681 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 682 | @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 HIGUCHI | 4f55c67 | 2018-06-14 18:10:43 -0700 | [diff] [blame] | 700 | @Override |
| 701 | protected boolean checkReply(String reply) { |
| 702 | // Overridden to record error logs |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 703 | 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 HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame] | 710 | // FIXME rpc-error with a warning is considered same as Ok?? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 711 | 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 zhao | 78eab37 | 2018-08-27 16:22:39 +0800 | [diff] [blame] | 719 | @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 Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 736 | protected void publishEvent(NetconfDeviceOutputEvent event) { |
| 737 | primaryListeners.forEach(lsnr -> { |
| 738 | if (lsnr.isRelevant(event)) { |
| 739 | lsnr.event(event); |
| 740 | } |
| 741 | }); |
| 742 | } |
| 743 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 744 | 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 Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 787 | publishEvent(event); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 788 | } |
| 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 Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 797 | replies.keySet()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 798 | if (!messageId.isPresent()) { |
| 799 | errorReplies.add(event.getMessagePayload()); |
| 800 | log.error("Device {} sent error reply {}", |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 801 | event.getDeviceInfo(), event.getMessagePayload()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 802 | return; |
| 803 | } |
| 804 | CompletableFuture<String> completedReply = |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 805 | replies.get(messageId.get()); // remove(..)? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 806 | if (completedReply != null) { |
| 807 | completedReply.complete(event.getMessagePayload()); |
| 808 | } |
| 809 | } |
| 810 | } |
| 811 | |
Yuta HIGUCHI | 2ee4fba | 2018-06-12 16:21:06 -0700 | [diff] [blame] | 812 | /** |
| 813 | * @deprecated in 1.14.0 |
| 814 | */ |
| 815 | @Deprecated |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 816 | 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 Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 823 | } |