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; |
| 24 | import org.apache.sshd.client.SshClient; |
| 25 | import org.apache.sshd.client.channel.ClientChannel; |
| 26 | import org.apache.sshd.client.future.ConnectFuture; |
| 27 | import org.apache.sshd.client.future.OpenFuture; |
| 28 | import org.apache.sshd.client.session.ClientSession; |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 29 | import org.apache.sshd.common.FactoryManager; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 30 | import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; |
Holger Schulz | 092cbbf | 2017-08-31 17:52:30 +0200 | [diff] [blame] | 31 | import org.bouncycastle.jce.provider.BouncyCastleProvider; |
| 32 | import org.bouncycastle.openssl.PEMParser; |
| 33 | import org.bouncycastle.openssl.PEMKeyPair; |
| 34 | import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 35 | import org.onlab.util.SharedExecutors; |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 36 | import org.onosproject.netconf.DatastoreId; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 37 | import org.onosproject.netconf.NetconfDeviceInfo; |
| 38 | import org.onosproject.netconf.NetconfDeviceOutputEvent; |
| 39 | import org.onosproject.netconf.NetconfDeviceOutputEvent.Type; |
| 40 | import org.onosproject.netconf.NetconfDeviceOutputEventListener; |
| 41 | import org.onosproject.netconf.NetconfException; |
| 42 | import org.onosproject.netconf.NetconfSession; |
| 43 | import org.onosproject.netconf.NetconfSessionFactory; |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 44 | import org.onosproject.netconf.NetconfTransportException; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 45 | import org.slf4j.Logger; |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 46 | import static java.nio.charset.StandardCharsets.UTF_8; |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 47 | import static org.slf4j.LoggerFactory.getLogger; |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 48 | |
Holger Schulz | 092cbbf | 2017-08-31 17:52:30 +0200 | [diff] [blame] | 49 | import java.io.CharArrayReader; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 50 | import java.io.IOException; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 51 | import java.security.KeyFactory; |
| 52 | import java.security.KeyPair; |
| 53 | import java.security.NoSuchAlgorithmException; |
| 54 | import java.security.PublicKey; |
| 55 | import java.security.spec.InvalidKeySpecException; |
| 56 | import java.security.spec.X509EncodedKeySpec; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 57 | import java.util.LinkedHashSet; |
| 58 | import java.util.Map; |
| 59 | import java.util.Set; |
| 60 | import java.util.List; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 61 | import java.util.Collection; |
| 62 | import java.util.Collections; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 63 | import java.util.Optional; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 64 | import java.util.ArrayList; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 65 | import java.util.concurrent.CompletableFuture; |
| 66 | import java.util.concurrent.ConcurrentHashMap; |
| 67 | import java.util.concurrent.CopyOnWriteArrayList; |
| 68 | import java.util.concurrent.ExecutionException; |
| 69 | import java.util.concurrent.TimeUnit; |
| 70 | import java.util.concurrent.TimeoutException; |
| 71 | import java.util.concurrent.atomic.AtomicInteger; |
| 72 | import java.util.regex.Matcher; |
| 73 | import java.util.regex.Pattern; |
| 74 | |
| 75 | /** |
| 76 | * Implementation of a NETCONF session to talk to a device. |
| 77 | */ |
| 78 | public class NetconfSessionMinaImpl implements NetconfSession { |
| 79 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 80 | private static final Logger log = getLogger(NetconfSessionMinaImpl.class); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 81 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 82 | /** |
| 83 | * NC 1.0, RFC4742 EOM sequence. |
| 84 | */ |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 85 | private static final String ENDPATTERN = "]]>]]>"; |
| 86 | private static final String MESSAGE_ID_STRING = "message-id"; |
| 87 | private static final String HELLO = "<hello"; |
| 88 | private static final String NEW_LINE = "\n"; |
| 89 | private static final String END_OF_RPC_OPEN_TAG = "\">"; |
| 90 | private static final String EQUAL = "="; |
| 91 | private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\""; |
| 92 | private static final String RPC_OPEN = "<rpc "; |
| 93 | private static final String RPC_CLOSE = "</rpc>"; |
| 94 | private static final String GET_OPEN = "<get>"; |
| 95 | private static final String GET_CLOSE = "</get>"; |
| 96 | private static final String WITH_DEFAULT_OPEN = "<with-defaults "; |
| 97 | private static final String WITH_DEFAULT_CLOSE = "</with-defaults>"; |
| 98 | private static final String DEFAULT_OPERATION_OPEN = "<default-operation>"; |
| 99 | private static final String DEFAULT_OPERATION_CLOSE = "</default-operation>"; |
| 100 | private static final String SUBTREE_FILTER_OPEN = "<filter type=\"subtree\">"; |
| 101 | private static final String SUBTREE_FILTER_CLOSE = "</filter>"; |
| 102 | private static final String EDIT_CONFIG_OPEN = "<edit-config>"; |
| 103 | private static final String EDIT_CONFIG_CLOSE = "</edit-config>"; |
| 104 | private static final String TARGET_OPEN = "<target>"; |
| 105 | private static final String TARGET_CLOSE = "</target>"; |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 106 | // FIXME hard coded namespace nc |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 107 | private static final String CONFIG_OPEN = "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"; |
| 108 | private static final String CONFIG_CLOSE = "</config>"; |
| 109 | private static final String XML_HEADER = |
| 110 | "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; |
| 111 | private static final String NETCONF_BASE_NAMESPACE = |
| 112 | "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""; |
| 113 | private static final String NETCONF_WITH_DEFAULTS_NAMESPACE = |
| 114 | "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\""; |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 115 | // FIXME hard coded namespace base10 |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 116 | private static final String SUBSCRIPTION_SUBTREE_FILTER_OPEN = |
| 117 | "<filter xmlns:base10=\"urn:ietf:params:xml:ns:netconf:base:1.0\" base10:type=\"subtree\">"; |
| 118 | |
| 119 | private static final String INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0"; |
| 120 | |
| 121 | private static final String CAPABILITY_REGEX = "<capability>\\s*(.*?)\\s*</capability>"; |
| 122 | private static final Pattern CAPABILITY_REGEX_PATTERN = Pattern.compile(CAPABILITY_REGEX); |
| 123 | |
| 124 | private static final String SESSION_ID_REGEX = "<session-id>\\s*(.*?)\\s*</session-id>"; |
| 125 | private static final Pattern SESSION_ID_REGEX_PATTERN = Pattern.compile(SESSION_ID_REGEX); |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 126 | private static final String HASH = "#"; |
| 127 | private static final String LF = "\n"; |
| 128 | private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n"; |
| 129 | private static final String NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0"; |
| 130 | private static final String NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1"; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 131 | |
| 132 | private String sessionID; |
| 133 | private final AtomicInteger messageIdInteger = new AtomicInteger(1); |
| 134 | protected final NetconfDeviceInfo deviceInfo; |
| 135 | private Iterable<String> onosCapabilities = |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 136 | ImmutableList.of(NETCONF_10_CAPABILITY, NETCONF_11_CAPABILITY); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 137 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 138 | private final Set<String> deviceCapabilities = new LinkedHashSet<>(); |
| 139 | private NetconfStreamHandler streamHandler; |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 140 | // FIXME ONOS-7019 key type should be revised to a String, see RFC6241 |
| 141 | /** |
| 142 | * Message-ID and corresponding Future waiting for response. |
| 143 | */ |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 144 | private Map<Integer, CompletableFuture<String>> replies; |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 145 | private List<String> errorReplies; // Not sure why we need this? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 146 | private boolean subscriptionConnected = false; |
| 147 | private String notificationFilterSchema = null; |
| 148 | |
| 149 | private final Collection<NetconfDeviceOutputEventListener> primaryListeners = |
| 150 | new CopyOnWriteArrayList<>(); |
| 151 | private final Collection<NetconfSession> children = |
| 152 | new CopyOnWriteArrayList<>(); |
| 153 | |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 154 | private int connectTimeout; |
| 155 | private int replyTimeout; |
| 156 | private int idleTimeout; |
| 157 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 158 | |
| 159 | private ClientChannel channel = null; |
| 160 | private ClientSession session = null; |
| 161 | private SshClient client = null; |
| 162 | |
| 163 | |
| 164 | public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException { |
| 165 | this.deviceInfo = deviceInfo; |
| 166 | replies = new ConcurrentHashMap<>(); |
| 167 | errorReplies = new ArrayList<>(); |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 168 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 169 | // FIXME should not immediately start session on construction |
| 170 | // setOnosCapabilities() is useless due to this behavior |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 171 | startConnection(); |
| 172 | } |
| 173 | |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 174 | public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo, List<String> capabilities) throws NetconfException { |
| 175 | this.deviceInfo = deviceInfo; |
| 176 | replies = new ConcurrentHashMap<>(); |
| 177 | errorReplies = new ArrayList<>(); |
| 178 | setOnosCapabilities(capabilities); |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 179 | // FIXME should not immediately start session on construction |
| 180 | // setOnosCapabilities() is useless due to this behavior |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 181 | startConnection(); |
| 182 | } |
| 183 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 184 | private void startConnection() throws NetconfException { |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 185 | connectTimeout = deviceInfo.getConnectTimeoutSec().orElse( |
| 186 | NetconfControllerImpl.netconfConnectTimeout); |
| 187 | replyTimeout = deviceInfo.getReplyTimeoutSec().orElse( |
| 188 | NetconfControllerImpl.netconfReplyTimeout); |
| 189 | idleTimeout = deviceInfo.getIdleTimeoutSec().orElse( |
| 190 | NetconfControllerImpl.netconfIdleTimeout); |
| 191 | log.info("Connecting to {} with timeouts C:{}, R:{}, I:{}", deviceInfo, |
| 192 | connectTimeout, replyTimeout, idleTimeout); |
| 193 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 194 | try { |
| 195 | startClient(); |
| 196 | } catch (IOException e) { |
| 197 | throw new NetconfException("Failed to establish SSH with device " + deviceInfo, e); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | private void startClient() throws IOException { |
| 202 | client = SshClient.setUpDefaultClient(); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 203 | client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT, |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 204 | TimeUnit.SECONDS.toMillis(idleTimeout)); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 205 | client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 206 | TimeUnit.SECONDS.toMillis(idleTimeout + 15L)); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 207 | client.start(); |
| 208 | client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider()); |
| 209 | startSession(); |
| 210 | } |
| 211 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 212 | // FIXME blocking |
| 213 | @Deprecated |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 214 | private void startSession() throws IOException { |
| 215 | final ConnectFuture connectFuture; |
| 216 | connectFuture = client.connect(deviceInfo.name(), |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 217 | deviceInfo.ip().toString(), |
| 218 | deviceInfo.port()) |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 219 | .verify(connectTimeout, TimeUnit.SECONDS); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 220 | session = connectFuture.getSession(); |
| 221 | //Using the device ssh key if possible |
| 222 | if (deviceInfo.getKey() != null) { |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 223 | try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) { |
| 224 | JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME); |
| 225 | try { |
| 226 | KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject()); |
| 227 | session.addPublicKeyIdentity(kp); |
| 228 | } catch (IOException e) { |
| 229 | throw new NetconfException("Failed to authenticate session with device " + |
| 230 | deviceInfo + "check key to be a valid key", e); |
| 231 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 232 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 233 | } else { |
| 234 | session.addPasswordIdentity(deviceInfo.password()); |
| 235 | } |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 236 | session.auth().verify(connectTimeout, TimeUnit.SECONDS); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 237 | Set<ClientSession.ClientSessionEvent> event = session.waitFor( |
| 238 | ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 239 | ClientSession.ClientSessionEvent.CLOSED, |
| 240 | ClientSession.ClientSessionEvent.AUTHED), 0); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 241 | |
| 242 | if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) { |
| 243 | log.debug("Session closed {} {}", event, session.isClosed()); |
| 244 | throw new NetconfException("Failed to authenticate session with device " + |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 245 | deviceInfo + "check the user/pwd or key"); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 246 | } |
| 247 | openChannel(); |
| 248 | } |
| 249 | |
| 250 | private PublicKey getPublicKey(byte[] keyBytes, String type) |
| 251 | throws NoSuchAlgorithmException, InvalidKeySpecException { |
| 252 | |
| 253 | X509EncodedKeySpec spec = |
| 254 | new X509EncodedKeySpec(keyBytes); |
| 255 | KeyFactory kf = KeyFactory.getInstance(type); |
| 256 | return kf.generatePublic(spec); |
| 257 | } |
| 258 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 259 | // FIXME blocking |
| 260 | @Deprecated |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 261 | private void openChannel() throws IOException { |
| 262 | channel = session.createSubsystemChannel("netconf"); |
| 263 | OpenFuture channelFuture = channel.open(); |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 264 | if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 265 | if (channelFuture.isOpened()) { |
| 266 | streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(), |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 267 | channel.getInvertedErr(), deviceInfo, |
| 268 | new NetconfSessionDelegateImpl(), replies); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 269 | } else { |
| 270 | throw new NetconfException("Failed to open channel with device " + |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 271 | deviceInfo); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 272 | } |
| 273 | sendHello(); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | |
| 278 | @Beta |
| 279 | protected void startSubscriptionStream(String filterSchema) throws NetconfException { |
| 280 | boolean openNewSession = false; |
| 281 | if (!deviceCapabilities.contains(INTERLEAVE_CAPABILITY_STRING)) { |
| 282 | log.info("Device {} doesn't support interleave, creating child session", deviceInfo); |
| 283 | openNewSession = true; |
| 284 | |
| 285 | } else if (subscriptionConnected && |
| 286 | notificationFilterSchema != null && |
| 287 | !Objects.equal(filterSchema, notificationFilterSchema)) { |
| 288 | // interleave supported and existing filter is NOT "no filtering" |
| 289 | // and was requested with different filtering schema |
| 290 | log.info("Cannot use existing session for subscription {} ({})", |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 291 | deviceInfo, filterSchema); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 292 | openNewSession = true; |
| 293 | } |
| 294 | |
| 295 | if (openNewSession) { |
| 296 | log.info("Creating notification session to {} with filter {}", |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 297 | deviceInfo, filterSchema); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 298 | NetconfSession child = new NotificationSession(deviceInfo); |
| 299 | |
| 300 | child.addDeviceOutputListener(new NotificationForwarder()); |
| 301 | |
| 302 | child.startSubscription(filterSchema); |
| 303 | children.add(child); |
| 304 | return; |
| 305 | } |
| 306 | |
| 307 | // request to start interleaved notification session |
| 308 | String reply = sendRequest(createSubscriptionString(filterSchema)); |
| 309 | if (!checkReply(reply)) { |
| 310 | throw new NetconfException("Subscription not successful with device " |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 311 | + deviceInfo + " with reply " + reply); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 312 | } |
| 313 | subscriptionConnected = true; |
| 314 | } |
| 315 | |
| 316 | @Override |
| 317 | public void startSubscription() throws NetconfException { |
| 318 | if (!subscriptionConnected) { |
| 319 | startSubscriptionStream(null); |
| 320 | } |
| 321 | streamHandler.setEnableNotifications(true); |
| 322 | } |
| 323 | |
| 324 | @Beta |
| 325 | @Override |
| 326 | public void startSubscription(String filterSchema) throws NetconfException { |
| 327 | if (!subscriptionConnected) { |
| 328 | notificationFilterSchema = filterSchema; |
| 329 | startSubscriptionStream(filterSchema); |
| 330 | } |
| 331 | streamHandler.setEnableNotifications(true); |
| 332 | } |
| 333 | |
| 334 | @Beta |
| 335 | protected String createSubscriptionString(String filterSchema) { |
| 336 | StringBuilder subscriptionbuffer = new StringBuilder(); |
| 337 | subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); |
| 338 | subscriptionbuffer.append(" <create-subscription\n"); |
| 339 | subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n"); |
| 340 | // FIXME Only subtree filtering supported at the moment. |
| 341 | if (filterSchema != null) { |
| 342 | subscriptionbuffer.append(" "); |
| 343 | subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE); |
| 344 | subscriptionbuffer.append(filterSchema).append(NEW_LINE); |
| 345 | subscriptionbuffer.append(" "); |
| 346 | subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE); |
| 347 | } |
| 348 | subscriptionbuffer.append(" </create-subscription>\n"); |
| 349 | subscriptionbuffer.append("</rpc>\n"); |
| 350 | subscriptionbuffer.append(ENDPATTERN); |
| 351 | return subscriptionbuffer.toString(); |
| 352 | } |
| 353 | |
| 354 | @Override |
| 355 | public void endSubscription() throws NetconfException { |
| 356 | if (subscriptionConnected) { |
| 357 | streamHandler.setEnableNotifications(false); |
| 358 | } else { |
| 359 | throw new NetconfException("Subscription does not exist."); |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | private void sendHello() throws NetconfException { |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 364 | String serverHelloResponse = sendRequest(createHelloString(), true); |
| 365 | Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 366 | while (capabilityMatcher.find()) { |
| 367 | deviceCapabilities.add(capabilityMatcher.group(1)); |
| 368 | } |
| 369 | sessionID = String.valueOf(-1); |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 370 | Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 371 | if (sessionIDMatcher.find()) { |
| 372 | sessionID = sessionIDMatcher.group(1); |
| 373 | } else { |
| 374 | throw new NetconfException("Missing SessionID in server hello " + |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 375 | "reponse."); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 376 | } |
| 377 | |
| 378 | } |
| 379 | |
| 380 | private String createHelloString() { |
| 381 | StringBuilder hellobuffer = new StringBuilder(); |
| 382 | hellobuffer.append(XML_HEADER); |
| 383 | hellobuffer.append("\n"); |
| 384 | hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); |
| 385 | hellobuffer.append(" <capabilities>\n"); |
| 386 | onosCapabilities.forEach( |
| 387 | cap -> hellobuffer.append(" <capability>") |
| 388 | .append(cap) |
| 389 | .append("</capability>\n")); |
| 390 | hellobuffer.append(" </capabilities>\n"); |
| 391 | hellobuffer.append("</hello>\n"); |
| 392 | hellobuffer.append(ENDPATTERN); |
| 393 | return hellobuffer.toString(); |
| 394 | |
| 395 | } |
| 396 | |
| 397 | @Override |
| 398 | public void checkAndReestablish() throws NetconfException { |
| 399 | try { |
| 400 | if (client.isClosed()) { |
| 401 | log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId()); |
| 402 | cleanUp(); |
| 403 | startConnection(); |
| 404 | } else if (session.isClosed()) { |
| 405 | log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId()); |
| 406 | cleanUp(); |
| 407 | startSession(); |
| 408 | } else if (channel.isClosed()) { |
| 409 | log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId()); |
| 410 | cleanUp(); |
| 411 | openChannel(); |
| 412 | } |
| 413 | if (subscriptionConnected) { |
| 414 | log.debug("Restarting subscription with {}", deviceInfo.getDeviceId()); |
| 415 | subscriptionConnected = false; |
| 416 | startSubscription(notificationFilterSchema); |
| 417 | } |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 418 | } catch (IOException | IllegalStateException e) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 419 | log.error("Can't reopen connection for device {}", e.getMessage()); |
| 420 | throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | private void cleanUp() { |
| 425 | //makes sure everything is at a clean state. |
| 426 | replies.clear(); |
| 427 | } |
| 428 | |
| 429 | @Override |
| 430 | public String requestSync(String request) throws NetconfException { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 431 | String reply = sendRequest(request); |
| 432 | checkReply(reply); |
| 433 | return reply; |
| 434 | } |
| 435 | |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 436 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 437 | // FIXME rename to align with what it actually do |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 438 | /** |
| 439 | * Validate and format netconf message. |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 440 | * - NC1.0 if no EOM sequence present on {@code message}, append. |
| 441 | * - NC1.1 chunk-encode given message unless it already is chunk encoded |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 442 | * |
| 443 | * @param message to format |
| 444 | * @return formated message |
| 445 | */ |
| 446 | private String formatNetconfMessage(String message) { |
| 447 | if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) { |
| 448 | message = formatChunkedMessage(message); |
| 449 | } else { |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 450 | if (!message.endsWith(ENDPATTERN)) { |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 451 | message = message + NEW_LINE + ENDPATTERN; |
| 452 | } |
| 453 | } |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 454 | return message; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 455 | } |
| 456 | |
| 457 | /** |
| 458 | * Validate and format message according to chunked framing mechanism. |
| 459 | * |
| 460 | * @param message to format |
| 461 | * @return formated message |
| 462 | */ |
| 463 | private String formatChunkedMessage(String message) { |
| 464 | if (message.endsWith(ENDPATTERN)) { |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 465 | // message given had Netconf 1.0 EOM pattern -> remove |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 466 | message = message.substring(0, message.length() - ENDPATTERN.length()); |
| 467 | } |
| 468 | if (!message.startsWith(LF + HASH)) { |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 469 | // chunk encode message |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 470 | 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] | 471 | } |
| 472 | return message; |
| 473 | } |
| 474 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 475 | @Override |
| 476 | @Deprecated |
| 477 | public CompletableFuture<String> request(String request) { |
| 478 | return streamHandler.sendMessage(request); |
| 479 | } |
| 480 | |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 481 | /** |
| 482 | * {@inheritDoc} |
| 483 | * <p> |
| 484 | * FIXME Note: as of 1.12.0 |
| 485 | * {@code request} must not include message-id, this method will assign |
| 486 | * and insert message-id on it's own. |
| 487 | * Will require ONOS-7019 to remove this limitation. |
| 488 | */ |
| 489 | @Override |
| 490 | public CompletableFuture<String> rpc(String request) { |
| 491 | |
| 492 | String rpc = request; |
| 493 | // - assign message-id |
| 494 | int msgId = messageIdInteger.incrementAndGet(); |
| 495 | // - re-write request to insert message-id |
| 496 | // FIXME avoid using formatRequestMessageId |
| 497 | rpc = formatRequestMessageId(rpc, msgId); |
| 498 | // - ensure it contains XML header |
| 499 | rpc = formatXmlHeader(rpc); |
| 500 | // - use chunked framing if talking to NC 1.1 device |
| 501 | // FIXME avoid using formatNetconfMessage |
| 502 | rpc = formatNetconfMessage(rpc); |
| 503 | |
| 504 | // TODO session liveness check & recovery |
| 505 | |
| 506 | log.debug("Sending {} to {}", rpc, this.deviceInfo.getDeviceId()); |
| 507 | return streamHandler.sendMessage(rpc, msgId) |
| 508 | .handleAsync((reply, t) -> { |
| 509 | if (t != null) { |
| 510 | // secure transport-layer error |
| 511 | // cannot use NetconfException, which is |
| 512 | // checked Exception. |
| 513 | throw new NetconfTransportException(t); |
| 514 | } else { |
| 515 | // FIXME avoid using checkReply, error handling is weird |
| 516 | checkReply(reply); |
| 517 | return reply; |
| 518 | } |
| 519 | }, SharedExecutors.getPoolThreadExecutor()); |
| 520 | } |
| 521 | |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 522 | @Override |
| 523 | public int timeoutConnectSec() { |
| 524 | return connectTimeout; |
| 525 | } |
| 526 | |
| 527 | @Override |
| 528 | public int timeoutReplySec() { |
| 529 | return replyTimeout; |
| 530 | } |
| 531 | |
| 532 | @Override |
| 533 | public int timeoutIdleSec() { |
| 534 | return idleTimeout; |
| 535 | } |
| 536 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 537 | private CompletableFuture<String> request(String request, int messageId) { |
| 538 | return streamHandler.sendMessage(request, messageId); |
| 539 | } |
| 540 | |
| 541 | private String sendRequest(String request) throws NetconfException { |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 542 | // FIXME probably chunk-encoding too early |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 543 | request = formatNetconfMessage(request); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 544 | return sendRequest(request, false); |
| 545 | } |
| 546 | |
| 547 | private String sendRequest(String request, boolean isHello) throws NetconfException { |
| 548 | checkAndReestablish(); |
| 549 | int messageId = -1; |
| 550 | if (!isHello) { |
| 551 | messageId = messageIdInteger.getAndIncrement(); |
| 552 | } |
Yuta HIGUCHI | b2d0524 | 2017-09-05 15:44:34 -0700 | [diff] [blame] | 553 | // FIXME potentially re-writing chunked encoded String? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 554 | request = formatXmlHeader(request); |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 555 | request = formatRequestMessageId(request, messageId); |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 556 | log.debug("Sending request to NETCONF with timeout {} for {}", |
| 557 | replyTimeout, deviceInfo.name()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 558 | CompletableFuture<String> futureReply = request(request, messageId); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 559 | String rp; |
| 560 | try { |
| 561 | rp = futureReply.get(replyTimeout, TimeUnit.SECONDS); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 562 | replies.remove(messageId); // Why here??? |
| 563 | } catch (InterruptedException e) { |
| 564 | Thread.currentThread().interrupt(); |
| 565 | throw new NetconfException("Interrupted waiting for reply for request" + request, e); |
| 566 | } catch (TimeoutException e) { |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 567 | throw new NetconfException("Timed out waiting for reply for request " + |
| 568 | request + " after " + replyTimeout + " sec.", e); |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 569 | } catch (ExecutionException e) { |
| 570 | log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e); |
| 571 | try { |
| 572 | session.close(); |
| 573 | channel.close(); //Closes the socket which should interrupt NetconfStreamThread |
| 574 | client.close(); |
| 575 | } catch (IOException ioe) { |
| 576 | log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe); |
| 577 | } |
| 578 | NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent( |
| 579 | NetconfDeviceOutputEvent.Type.SESSION_CLOSED, |
| 580 | null, "Closed due to unexpected error " + e.getCause(), |
| 581 | Optional.of(-1), deviceInfo); |
| 582 | publishEvent(event); |
| 583 | errorReplies.clear(); // move to cleanUp()? |
| 584 | cleanUp(); |
| 585 | |
| 586 | throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo + |
| 587 | " for request " + request, e); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 588 | } |
| 589 | log.debug("Result {} from request {} to device {}", rp, request, deviceInfo); |
| 590 | return rp.trim(); |
| 591 | } |
| 592 | |
| 593 | private String formatRequestMessageId(String request, int messageId) { |
| 594 | if (request.contains(MESSAGE_ID_STRING)) { |
| 595 | //FIXME if application provides his own counting of messages this fails that count |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 596 | // 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] | 597 | request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER, |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 598 | MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\""); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 599 | } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) { |
| 600 | //FIXME find out a better way to enforce the presence of message-id |
| 601 | request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\"" |
| 602 | + messageId + "\"" + ">"); |
| 603 | } |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 604 | request = updateRequestLength(request); |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 605 | return request; |
| 606 | } |
| 607 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 608 | private String updateRequestLength(String request) { |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 609 | if (request.contains(LF + HASH + HASH + LF)) { |
| 610 | int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]); |
| 611 | String rpcWithEnding = request.substring(request.indexOf('<')); |
| 612 | String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0]; |
| 613 | int newLen = 0; |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 614 | newLen = firstBlock.getBytes(UTF_8).length; |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 615 | if (oldLen != newLen) { |
| 616 | return LF + HASH + newLen + LF + rpcWithEnding; |
| 617 | } |
| 618 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 619 | return request; |
| 620 | } |
| 621 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 622 | /** |
| 623 | * Ensures xml start directive/declaration appears in the {@code request}. |
| 624 | * @param request RPC request message |
| 625 | * @return XML RPC message |
| 626 | */ |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 627 | private String formatXmlHeader(String request) { |
Sean Condon | 2d64717 | 2017-09-19 12:29:13 +0100 | [diff] [blame] | 628 | if (!request.contains(XML_HEADER)) { |
Yuta HIGUCHI | 1567798 | 2017-08-16 15:50:29 -0700 | [diff] [blame] | 629 | //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] | 630 | if (request.startsWith(LF + HASH)) { |
| 631 | request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length()); |
| 632 | } else { |
| 633 | request = XML_HEADER + "\n" + request; |
| 634 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 635 | } |
| 636 | return request; |
| 637 | } |
| 638 | |
| 639 | @Override |
| 640 | public String doWrappedRpc(String request) throws NetconfException { |
| 641 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 642 | rpc.append(RPC_OPEN); |
| 643 | rpc.append(MESSAGE_ID_STRING); |
| 644 | rpc.append(EQUAL); |
| 645 | rpc.append("\""); |
| 646 | rpc.append(messageIdInteger.get()); |
| 647 | rpc.append("\" "); |
| 648 | rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); |
| 649 | rpc.append(request); |
| 650 | rpc.append(RPC_CLOSE).append(NEW_LINE); |
| 651 | rpc.append(ENDPATTERN); |
| 652 | String reply = sendRequest(rpc.toString()); |
| 653 | checkReply(reply); |
| 654 | return reply; |
| 655 | } |
| 656 | |
| 657 | @Override |
| 658 | public String get(String request) throws NetconfException { |
| 659 | return requestSync(request); |
| 660 | } |
| 661 | |
| 662 | @Override |
| 663 | public String get(String filterSchema, String withDefaultsMode) throws NetconfException { |
| 664 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 665 | rpc.append(RPC_OPEN); |
| 666 | rpc.append(MESSAGE_ID_STRING); |
| 667 | rpc.append(EQUAL); |
| 668 | rpc.append("\""); |
| 669 | rpc.append(messageIdInteger.get()); |
| 670 | rpc.append("\" "); |
| 671 | rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); |
| 672 | rpc.append(GET_OPEN).append(NEW_LINE); |
| 673 | if (filterSchema != null) { |
| 674 | rpc.append(SUBTREE_FILTER_OPEN).append(NEW_LINE); |
| 675 | rpc.append(filterSchema).append(NEW_LINE); |
| 676 | rpc.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE); |
| 677 | } |
| 678 | if (withDefaultsMode != null) { |
| 679 | rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">"); |
| 680 | rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE); |
| 681 | } |
| 682 | rpc.append(GET_CLOSE).append(NEW_LINE); |
| 683 | rpc.append(RPC_CLOSE).append(NEW_LINE); |
| 684 | rpc.append(ENDPATTERN); |
| 685 | String reply = sendRequest(rpc.toString()); |
| 686 | checkReply(reply); |
| 687 | return reply; |
| 688 | } |
| 689 | |
| 690 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 691 | public String getConfig(DatastoreId netconfTargetConfig) throws NetconfException { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 692 | return getConfig(netconfTargetConfig, null); |
| 693 | } |
| 694 | |
| 695 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 696 | public String getConfig(DatastoreId netconfTargetConfig, |
| 697 | String configurationSchema) throws NetconfException { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 698 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 699 | rpc.append("<rpc "); |
| 700 | rpc.append(MESSAGE_ID_STRING); |
| 701 | rpc.append(EQUAL); |
| 702 | rpc.append("\""); |
| 703 | rpc.append(messageIdInteger.get()); |
| 704 | rpc.append("\" "); |
| 705 | rpc.append("xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); |
| 706 | rpc.append("<get-config>\n"); |
| 707 | rpc.append("<source>\n"); |
| 708 | rpc.append("<").append(netconfTargetConfig).append("/>"); |
| 709 | rpc.append("</source>"); |
| 710 | if (configurationSchema != null) { |
| 711 | rpc.append("<filter type=\"subtree\">\n"); |
| 712 | rpc.append(configurationSchema).append("\n"); |
| 713 | rpc.append("</filter>\n"); |
| 714 | } |
| 715 | rpc.append("</get-config>\n"); |
| 716 | rpc.append("</rpc>\n"); |
| 717 | rpc.append(ENDPATTERN); |
| 718 | String reply = sendRequest(rpc.toString()); |
| 719 | return checkReply(reply) ? reply : "ERROR " + reply; |
| 720 | } |
| 721 | |
| 722 | @Override |
| 723 | public boolean editConfig(String newConfiguration) throws NetconfException { |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 724 | if (!newConfiguration.endsWith(ENDPATTERN)) { |
| 725 | newConfiguration = newConfiguration + ENDPATTERN; |
| 726 | } |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 727 | return checkReply(sendRequest(newConfiguration)); |
| 728 | } |
| 729 | |
| 730 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 731 | public boolean editConfig(DatastoreId netconfTargetConfig, |
| 732 | String mode, |
| 733 | String newConfiguration) |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 734 | throws NetconfException { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 735 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 736 | newConfiguration = newConfiguration.trim(); |
| 737 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 738 | rpc.append(RPC_OPEN); |
| 739 | rpc.append(MESSAGE_ID_STRING); |
| 740 | rpc.append(EQUAL); |
| 741 | rpc.append("\""); |
| 742 | rpc.append(messageIdInteger.get()); |
| 743 | rpc.append("\" "); |
| 744 | rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); |
| 745 | rpc.append(EDIT_CONFIG_OPEN).append("\n"); |
| 746 | rpc.append(TARGET_OPEN); |
| 747 | rpc.append("<").append(netconfTargetConfig).append("/>"); |
| 748 | rpc.append(TARGET_CLOSE).append("\n"); |
| 749 | if (mode != null) { |
| 750 | rpc.append(DEFAULT_OPERATION_OPEN); |
| 751 | rpc.append(mode); |
| 752 | rpc.append(DEFAULT_OPERATION_CLOSE).append("\n"); |
| 753 | } |
| 754 | rpc.append(CONFIG_OPEN).append("\n"); |
| 755 | rpc.append(newConfiguration); |
| 756 | rpc.append(CONFIG_CLOSE).append("\n"); |
| 757 | rpc.append(EDIT_CONFIG_CLOSE).append("\n"); |
| 758 | rpc.append(RPC_CLOSE); |
| 759 | rpc.append(ENDPATTERN); |
| 760 | log.debug(rpc.toString()); |
| 761 | String reply = sendRequest(rpc.toString()); |
| 762 | return checkReply(reply); |
| 763 | } |
| 764 | |
| 765 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 766 | public boolean copyConfig(DatastoreId destination, |
| 767 | DatastoreId source) |
| 768 | throws NetconfException { |
| 769 | return bareCopyConfig(destination.asXml(), source.asXml()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 770 | } |
| 771 | |
| 772 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 773 | public boolean copyConfig(DatastoreId netconfTargetConfig, |
| 774 | String newConfiguration) |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 775 | throws NetconfException { |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 776 | return bareCopyConfig(netconfTargetConfig.asXml(), |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 777 | normalizeCopyConfigParam(newConfiguration)); |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 778 | } |
| 779 | |
| 780 | @Override |
| 781 | public boolean copyConfig(String netconfTargetConfig, |
| 782 | String newConfiguration) throws NetconfException { |
| 783 | return bareCopyConfig(normalizeCopyConfigParam(netconfTargetConfig), |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 784 | normalizeCopyConfigParam(newConfiguration)); |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 785 | } |
| 786 | |
| 787 | /** |
| 788 | * Normalize String parameter passed to copy-config API. |
| 789 | * <p> |
| 790 | * Provided for backward compatibility purpose |
| 791 | * |
| 792 | * @param input passed to copyConfig API |
| 793 | * @return XML likely to be suitable for copy-config source or target |
| 794 | */ |
| 795 | private static CharSequence normalizeCopyConfigParam(String input) { |
| 796 | input = input.trim(); |
| 797 | if (input.startsWith("<url")) { |
| 798 | return input; |
| 799 | } else if (!input.startsWith("<")) { |
| 800 | // assume it is a datastore name |
| 801 | return DatastoreId.datastore(input).asXml(); |
| 802 | } else if (!input.startsWith("<config>")) { |
| 803 | return "<config>" + input + "</config>"; |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 804 | } |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 805 | return input; |
| 806 | } |
| 807 | |
| 808 | private boolean bareCopyConfig(CharSequence target, |
| 809 | CharSequence source) |
| 810 | throws NetconfException { |
| 811 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 812 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 813 | rpc.append(RPC_OPEN); |
| 814 | rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); |
| 815 | rpc.append("<copy-config>"); |
| 816 | rpc.append("<target>"); |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 817 | rpc.append(target); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 818 | rpc.append("</target>"); |
| 819 | rpc.append("<source>"); |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 820 | rpc.append(source); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 821 | rpc.append("</source>"); |
| 822 | rpc.append("</copy-config>"); |
| 823 | rpc.append("</rpc>"); |
| 824 | rpc.append(ENDPATTERN); |
| 825 | return checkReply(sendRequest(rpc.toString())); |
| 826 | } |
| 827 | |
| 828 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 829 | public boolean deleteConfig(DatastoreId netconfTargetConfig) throws NetconfException { |
| 830 | if (netconfTargetConfig.equals(DatastoreId.RUNNING)) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 831 | log.warn("Target configuration for delete operation can't be \"running\"", |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 832 | netconfTargetConfig); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 833 | return false; |
| 834 | } |
| 835 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 836 | rpc.append("<rpc>"); |
| 837 | rpc.append("<delete-config>"); |
| 838 | rpc.append("<target>"); |
| 839 | rpc.append("<").append(netconfTargetConfig).append("/>"); |
| 840 | rpc.append("</target>"); |
| 841 | rpc.append("</delete-config>"); |
| 842 | rpc.append("</rpc>"); |
| 843 | rpc.append(ENDPATTERN); |
| 844 | return checkReply(sendRequest(rpc.toString())); |
| 845 | } |
| 846 | |
| 847 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 848 | public boolean lock(DatastoreId configType) throws NetconfException { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 849 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 850 | rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); |
| 851 | rpc.append("<lock>"); |
| 852 | rpc.append("<target>"); |
| 853 | rpc.append("<"); |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 854 | rpc.append(configType.id()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 855 | rpc.append("/>"); |
| 856 | rpc.append("</target>"); |
| 857 | rpc.append("</lock>"); |
| 858 | rpc.append("</rpc>"); |
| 859 | rpc.append(ENDPATTERN); |
| 860 | String lockReply = sendRequest(rpc.toString()); |
| 861 | return checkReply(lockReply); |
| 862 | } |
| 863 | |
| 864 | @Override |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 865 | public boolean unlock(DatastoreId configType) throws NetconfException { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 866 | StringBuilder rpc = new StringBuilder(XML_HEADER); |
| 867 | rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); |
| 868 | rpc.append("<unlock>"); |
| 869 | rpc.append("<target>"); |
| 870 | rpc.append("<"); |
Yuta HIGUCHI | 26c397c | 2017-05-19 12:52:28 -0700 | [diff] [blame] | 871 | rpc.append(configType.id()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 872 | rpc.append("/>"); |
| 873 | rpc.append("</target>"); |
| 874 | rpc.append("</unlock>"); |
| 875 | rpc.append("</rpc>"); |
| 876 | rpc.append(ENDPATTERN); |
| 877 | String unlockReply = sendRequest(rpc.toString()); |
| 878 | return checkReply(unlockReply); |
| 879 | } |
| 880 | |
| 881 | @Override |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 882 | public boolean close() throws NetconfException { |
| 883 | return close(false); |
| 884 | } |
| 885 | |
| 886 | private boolean close(boolean force) throws NetconfException { |
| 887 | StringBuilder rpc = new StringBuilder(); |
| 888 | rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"); |
| 889 | if (force) { |
| 890 | rpc.append("<kill-session/>"); |
| 891 | } else { |
| 892 | rpc.append("<close-session/>"); |
| 893 | } |
| 894 | rpc.append("</rpc>"); |
| 895 | rpc.append(ENDPATTERN); |
| 896 | return checkReply(sendRequest(rpc.toString())) || close(true); |
| 897 | } |
| 898 | |
| 899 | @Override |
| 900 | public String getSessionId() { |
| 901 | return sessionID; |
| 902 | } |
| 903 | |
| 904 | @Override |
| 905 | public Set<String> getDeviceCapabilitiesSet() { |
| 906 | return Collections.unmodifiableSet(deviceCapabilities); |
| 907 | } |
| 908 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 909 | @Override |
| 910 | public void setOnosCapabilities(Iterable<String> capabilities) { |
| 911 | onosCapabilities = capabilities; |
| 912 | } |
| 913 | |
| 914 | |
| 915 | @Override |
| 916 | public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) { |
| 917 | streamHandler.addDeviceEventListener(listener); |
| 918 | primaryListeners.add(listener); |
| 919 | } |
| 920 | |
| 921 | @Override |
| 922 | public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) { |
| 923 | primaryListeners.remove(listener); |
| 924 | streamHandler.removeDeviceEventListener(listener); |
| 925 | } |
| 926 | |
Yuta HIGUCHI | 371667d | 2017-09-05 17:30:51 -0700 | [diff] [blame] | 927 | private boolean checkReply(String reply) { |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 928 | if (reply != null) { |
| 929 | if (!reply.contains("<rpc-error>")) { |
| 930 | log.debug("Device {} sent reply {}", deviceInfo, reply); |
| 931 | return true; |
| 932 | } else if (reply.contains("<ok/>") |
| 933 | || (reply.contains("<rpc-error>") |
| 934 | && reply.contains("warning"))) { |
Yuta HIGUCHI | 6e6c26e | 2017-09-06 14:25:57 -0700 | [diff] [blame^] | 935 | // FIXME rpc-error with a warning is considered same as Ok?? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 936 | log.debug("Device {} sent reply {}", deviceInfo, reply); |
| 937 | return true; |
| 938 | } |
| 939 | } |
| 940 | log.warn("Device {} has error in reply {}", deviceInfo, reply); |
| 941 | return false; |
| 942 | } |
| 943 | |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 944 | protected void publishEvent(NetconfDeviceOutputEvent event) { |
| 945 | primaryListeners.forEach(lsnr -> { |
| 946 | if (lsnr.isRelevant(event)) { |
| 947 | lsnr.event(event); |
| 948 | } |
| 949 | }); |
| 950 | } |
| 951 | |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 952 | static class NotificationSession extends NetconfSessionMinaImpl { |
| 953 | |
| 954 | private String notificationFilter; |
| 955 | |
| 956 | NotificationSession(NetconfDeviceInfo deviceInfo) |
| 957 | throws NetconfException { |
| 958 | super(deviceInfo); |
| 959 | } |
| 960 | |
| 961 | @Override |
| 962 | protected void startSubscriptionStream(String filterSchema) |
| 963 | throws NetconfException { |
| 964 | |
| 965 | notificationFilter = filterSchema; |
| 966 | requestSync(createSubscriptionString(filterSchema)); |
| 967 | } |
| 968 | |
| 969 | @Override |
| 970 | public String toString() { |
| 971 | return MoreObjects.toStringHelper(getClass()) |
| 972 | .add("deviceInfo", deviceInfo) |
| 973 | .add("sessionID", getSessionId()) |
| 974 | .add("notificationFilter", notificationFilter) |
| 975 | .toString(); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | /** |
| 980 | * Listener attached to child session for notification streaming. |
| 981 | * <p> |
| 982 | * Forwards all notification event from child session to primary session |
| 983 | * listeners. |
| 984 | */ |
| 985 | private final class NotificationForwarder |
| 986 | implements NetconfDeviceOutputEventListener { |
| 987 | |
| 988 | @Override |
| 989 | public boolean isRelevant(NetconfDeviceOutputEvent event) { |
| 990 | return event.type() == Type.DEVICE_NOTIFICATION; |
| 991 | } |
| 992 | |
| 993 | @Override |
| 994 | public void event(NetconfDeviceOutputEvent event) { |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 995 | publishEvent(event); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 996 | } |
| 997 | } |
| 998 | |
| 999 | public class NetconfSessionDelegateImpl implements NetconfSessionDelegate { |
| 1000 | |
| 1001 | @Override |
| 1002 | public void notify(NetconfDeviceOutputEvent event) { |
| 1003 | Optional<Integer> messageId = event.getMessageID(); |
| 1004 | log.debug("messageID {}, waiting replies messageIDs {}", messageId, |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 1005 | replies.keySet()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 1006 | if (!messageId.isPresent()) { |
| 1007 | errorReplies.add(event.getMessagePayload()); |
| 1008 | log.error("Device {} sent error reply {}", |
Kamil Stasiak | 9f59f44 | 2017-05-02 11:02:24 +0200 | [diff] [blame] | 1009 | event.getDeviceInfo(), event.getMessagePayload()); |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 1010 | return; |
| 1011 | } |
| 1012 | CompletableFuture<String> completedReply = |
Sean Condon | 7347de9 | 2017-07-21 12:17:25 +0100 | [diff] [blame] | 1013 | replies.get(messageId.get()); // remove(..)? |
Andrea Campanella | 7bbe7b1 | 2017-05-03 16:03:38 -0700 | [diff] [blame] | 1014 | if (completedReply != null) { |
| 1015 | completedReply.complete(event.getMessagePayload()); |
| 1016 | } |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory { |
| 1021 | |
| 1022 | @Override |
| 1023 | public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException { |
| 1024 | return new NetconfSessionMinaImpl(netconfDeviceInfo); |
| 1025 | } |
| 1026 | } |
Sean Condon | 54d8243 | 2017-07-26 22:27:25 +0100 | [diff] [blame] | 1027 | } |