blob: 59cc125d06f72c9ba510cdc6262a32272076fc44 [file] [log] [blame]
andreaeb70a942015-10-16 21:34:46 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
andreaeb70a942015-10-16 21:34:46 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.netconf.ctl;
18
Akihiro Yamanouchi45122222016-07-15 13:13:11 +090019import com.google.common.annotations.Beta;
andreaeb70a942015-10-16 21:34:46 -070020import ch.ethz.ssh2.Connection;
21import ch.ethz.ssh2.Session;
22import com.google.common.base.Preconditions;
23import org.onosproject.netconf.NetconfDeviceInfo;
Andrea Campanella101417d2015-12-11 17:58:07 -080024import org.onosproject.netconf.NetconfDeviceOutputEvent;
25import org.onosproject.netconf.NetconfDeviceOutputEventListener;
26import org.onosproject.netconf.NetconfException;
andreaeb70a942015-10-16 21:34:46 -070027import org.onosproject.netconf.NetconfSession;
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
andreaeb70a942015-10-16 21:34:46 -070031import java.io.IOException;
Andreas Papazoisd4712e22016-02-10 15:59:55 +020032import java.util.ArrayList;
Andrea Campanella1cd641b2015-12-07 17:28:34 -080033import java.util.Collections;
Andrea Campanella101417d2015-12-11 17:58:07 -080034import java.util.HashMap;
andreaeb70a942015-10-16 21:34:46 -070035import java.util.List;
Andrea Campanella101417d2015-12-11 17:58:07 -080036import java.util.Map;
Andreas Papazoisd4712e22016-02-10 15:59:55 +020037import java.util.Optional;
Andrea Campanella101417d2015-12-11 17:58:07 -080038import java.util.concurrent.CompletableFuture;
Andrea Campanellab029b9e2016-01-29 11:05:36 -080039import java.util.concurrent.ExecutionException;
40import java.util.concurrent.TimeUnit;
41import java.util.concurrent.TimeoutException;
Andrea Campanella101417d2015-12-11 17:58:07 -080042import java.util.concurrent.atomic.AtomicInteger;
43
andreaeb70a942015-10-16 21:34:46 -070044
45/**
46 * Implementation of a NETCONF session to talk to a device.
47 */
48public class NetconfSessionImpl implements NetconfSession {
49
Andrea Campanella101417d2015-12-11 17:58:07 -080050 private static final Logger log = LoggerFactory
andreaeb70a942015-10-16 21:34:46 -070051 .getLogger(NetconfSessionImpl.class);
Andrea Campanella101417d2015-12-11 17:58:07 -080052
Andrea Campanella101417d2015-12-11 17:58:07 -080053 private static final String ENDPATTERN = "]]>]]>";
Andrea Campanella101417d2015-12-11 17:58:07 -080054 private static final String MESSAGE_ID_STRING = "message-id";
Andrea Campanella1311ea02016-03-04 17:51:25 -080055 private static final String HELLO = "<hello";
Andrea Campanella101417d2015-12-11 17:58:07 -080056 private static final String NEW_LINE = "\n";
Andrea Campanellab029b9e2016-01-29 11:05:36 -080057 private static final String END_OF_RPC_OPEN_TAG = "\">";
58 private static final String EQUAL = "=";
59 private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"";
Akihiro Yamanouchi5e5d4df2016-06-08 17:06:33 +090060 private static final String RPC_OPEN = "<rpc ";
61 private static final String RPC_CLOSE = "</rpc>";
62 private static final String GET_OPEN = "<get>";
63 private static final String GET_CLOSE = "</get>";
64 private static final String WITH_DEFAULT_OPEN = "<with-defaults ";
65 private static final String WITH_DEFAULT_CLOSE = "</with-defaults>";
Akihiro Yamanouchid4912842016-07-01 10:38:46 +090066 private static final String DEFAULT_OPERATION_OPEN = "<default-operation>";
67 private static final String DEFAULT_OPERATION_CLOSE = "</default-operation>";
Akihiro Yamanouchi45122222016-07-15 13:13:11 +090068 private static final String SUBTREE_FILTER_OPEN = "<filter type=\"subtree\">";
69 private static final String SUBTREE_FILTER_CLOSE = "</filter>";
Akihiro Yamanouchid4912842016-07-01 10:38:46 +090070 private static final String EDIT_CONFIG_OPEN = "<edit-config>";
71 private static final String EDIT_CONFIG_CLOSE = "</edit-config>";
72 private static final String TARGET_OPEN = "<target>";
73 private static final String TARGET_CLOSE = "</target>";
Sean Condonb0720e72017-01-10 12:29:02 +000074 private static final String CONFIG_OPEN = "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
Akihiro Yamanouchid4912842016-07-01 10:38:46 +090075 private static final String CONFIG_CLOSE = "</config>";
Andrea Campanellab029b9e2016-01-29 11:05:36 -080076 private static final String XML_HEADER =
77 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
Akihiro Yamanouchi5e5d4df2016-06-08 17:06:33 +090078 private static final String NETCONF_BASE_NAMESPACE =
79 "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"";
80 private static final String NETCONF_WITH_DEFAULTS_NAMESPACE =
81 "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\"";
Akihiro Yamanouchi45122222016-07-15 13:13:11 +090082 private static final String SUBSCRIPTION_SUBTREE_FILTER_OPEN =
83 "<filter xmlns:base10=\"urn:ietf:params:xml:ns:netconf:base:1.0\" base10:type=\"subtree\">";
andreaeb70a942015-10-16 21:34:46 -070084
Andrea Campanellab029b9e2016-01-29 11:05:36 -080085 private final AtomicInteger messageIdInteger = new AtomicInteger(0);
andreaeb70a942015-10-16 21:34:46 -070086 private Connection netconfConnection;
87 private NetconfDeviceInfo deviceInfo;
88 private Session sshSession;
89 private boolean connectionActive;
andreaeb70a942015-10-16 21:34:46 -070090 private List<String> deviceCapabilities =
Andrea Campanella1cd641b2015-12-07 17:28:34 -080091 Collections.singletonList("urn:ietf:params:netconf:base:1.0");
andreaeb70a942015-10-16 21:34:46 -070092 private String serverCapabilities;
helenyrwu0407c642016-06-09 12:01:30 -070093 private NetconfStreamHandler streamHandler;
Andrea Campanella101417d2015-12-11 17:58:07 -080094 private Map<Integer, CompletableFuture<String>> replies;
Andreas Papazoisd4712e22016-02-10 15:59:55 +020095 private List<String> errorReplies;
helenyrwu0407c642016-06-09 12:01:30 -070096 private boolean subscriptionConnected = false;
andreaeb70a942015-10-16 21:34:46 -070097
98
Andrea Campanella101417d2015-12-11 17:58:07 -080099 public NetconfSessionImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700100 this.deviceInfo = deviceInfo;
Akihiro Yamanouchi5e5d4df2016-06-08 17:06:33 +0900101 this.netconfConnection = null;
102 this.sshSession = null;
andreaeb70a942015-10-16 21:34:46 -0700103 connectionActive = false;
Andrea Campanella101417d2015-12-11 17:58:07 -0800104 replies = new HashMap<>();
Andreas Papazoisd4712e22016-02-10 15:59:55 +0200105 errorReplies = new ArrayList<>();
andreaeb70a942015-10-16 21:34:46 -0700106 startConnection();
107 }
108
Andrea Campanella101417d2015-12-11 17:58:07 -0800109 private void startConnection() throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700110 if (!connectionActive) {
111 netconfConnection = new Connection(deviceInfo.ip().toString(), deviceInfo.port());
Sean Condon334ad692016-12-13 17:56:56 +0000112 int connectTimeout = NetconfControllerImpl.netconfConnectTimeout;
113
Andrea Campanella101417d2015-12-11 17:58:07 -0800114 try {
Sean Condon334ad692016-12-13 17:56:56 +0000115 netconfConnection.connect(null, 1000 * connectTimeout, 1000 * connectTimeout);
Andrea Campanella101417d2015-12-11 17:58:07 -0800116 } catch (IOException e) {
117 throw new NetconfException("Cannot open a connection with device" + deviceInfo, e);
118 }
andreaeb70a942015-10-16 21:34:46 -0700119 boolean isAuthenticated;
120 try {
121 if (deviceInfo.getKeyFile() != null) {
122 isAuthenticated = netconfConnection.authenticateWithPublicKey(
123 deviceInfo.name(), deviceInfo.getKeyFile(),
124 deviceInfo.password());
125 } else {
Andrea Campanella101417d2015-12-11 17:58:07 -0800126 log.debug("Authenticating to device {} with username {}",
Andrea Campanella50d25212016-02-26 13:06:23 -0800127 deviceInfo.getDeviceId(), deviceInfo.name());
andreaeb70a942015-10-16 21:34:46 -0700128 isAuthenticated = netconfConnection.authenticateWithPassword(
129 deviceInfo.name(), deviceInfo.password());
130 }
131 } catch (IOException e) {
Ryan Goulding69524392016-12-03 13:21:20 -0500132 log.error("Authentication connection to device {} failed",
133 deviceInfo.getDeviceId(), e);
Andrea Campanella101417d2015-12-11 17:58:07 -0800134 throw new NetconfException("Authentication connection to device " +
135 deviceInfo.getDeviceId() + " failed", e);
andreaeb70a942015-10-16 21:34:46 -0700136 }
137
138 connectionActive = true;
139 Preconditions.checkArgument(isAuthenticated,
Andrea Campanellad264b492016-03-01 09:46:06 -0800140 "Authentication to device %s with username " +
141 "%s failed",
Andrea Campanella50d25212016-02-26 13:06:23 -0800142 deviceInfo.getDeviceId(), deviceInfo.name());
andreaeb70a942015-10-16 21:34:46 -0700143 startSshSession();
144 }
145 }
146
Andrea Campanella101417d2015-12-11 17:58:07 -0800147 private void startSshSession() throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700148 try {
149 sshSession = netconfConnection.openSession();
150 sshSession.startSubSystem("netconf");
helenyrwu0407c642016-06-09 12:01:30 -0700151 streamHandler = new NetconfStreamThread(sshSession.getStdout(), sshSession.getStdin(),
152 sshSession.getStderr(), deviceInfo,
153 new NetconfSessionDelegateImpl());
Andrea Campanella101417d2015-12-11 17:58:07 -0800154 this.addDeviceOutputListener(new NetconfDeviceOutputEventListenerImpl(deviceInfo));
andreaeb70a942015-10-16 21:34:46 -0700155 sendHello();
156 } catch (IOException e) {
Ryan Goulding69524392016-12-03 13:21:20 -0500157 log.error("Failed to create ch.ethz.ssh2.Session session.", e);
Andrea Campanella101417d2015-12-11 17:58:07 -0800158 throw new NetconfException("Failed to create ch.ethz.ssh2.Session session with device" +
159 deviceInfo, e);
andreaeb70a942015-10-16 21:34:46 -0700160 }
161 }
162
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900163
164 @Beta
165 private void startSubscriptionConnection(String filterSchema) throws NetconfException {
helenyrwu0407c642016-06-09 12:01:30 -0700166 if (!serverCapabilities.contains("interleave")) {
167 throw new NetconfException("Device" + deviceInfo + "does not support interleave");
168 }
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900169 String reply = sendRequest(createSubscriptionString(filterSchema));
helenyrwu0407c642016-06-09 12:01:30 -0700170 if (!checkReply(reply)) {
171 throw new NetconfException("Subscription not successful with device "
172 + deviceInfo + " with reply " + reply);
173 }
174 subscriptionConnected = true;
175 }
176
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900177 @Override
helenyrwu0407c642016-06-09 12:01:30 -0700178 public void startSubscription() throws NetconfException {
179 if (!subscriptionConnected) {
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900180 startSubscriptionConnection(null);
helenyrwu0407c642016-06-09 12:01:30 -0700181 }
182 streamHandler.setEnableNotifications(true);
183 }
184
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900185 @Beta
186 @Override
187 public void startSubscription(String filterSchema) throws NetconfException {
188 if (!subscriptionConnected) {
189 startSubscriptionConnection(filterSchema);
190 }
191 streamHandler.setEnableNotifications(true);
192 }
193
194 @Beta
195 private String createSubscriptionString(String filterSchema) {
helenyrwu0407c642016-06-09 12:01:30 -0700196 StringBuilder subscriptionbuffer = new StringBuilder();
197 subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
198 subscriptionbuffer.append(" <create-subscription\n");
199 subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n");
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900200 // FIXME Only subtree filtering supported at the moment.
201 if (filterSchema != null) {
202 subscriptionbuffer.append(" ");
203 subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE);
204 subscriptionbuffer.append(filterSchema).append(NEW_LINE);
205 subscriptionbuffer.append(" ");
206 subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
207 }
helenyrwu0407c642016-06-09 12:01:30 -0700208 subscriptionbuffer.append(" </create-subscription>\n");
209 subscriptionbuffer.append("</rpc>\n");
210 subscriptionbuffer.append(ENDPATTERN);
211 return subscriptionbuffer.toString();
212 }
213
214 @Override
215 public void endSubscription() throws NetconfException {
216 if (subscriptionConnected) {
217 streamHandler.setEnableNotifications(false);
218 } else {
219 throw new NetconfException("Subscription does not exist.");
220 }
221 }
222
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800223 private void sendHello() throws NetconfException {
Andrea Campanella101417d2015-12-11 17:58:07 -0800224 serverCapabilities = sendRequest(createHelloString());
andreaeb70a942015-10-16 21:34:46 -0700225 }
226
227 private String createHelloString() {
228 StringBuilder hellobuffer = new StringBuilder();
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800229 hellobuffer.append(XML_HEADER);
230 hellobuffer.append("\n");
andreaeb70a942015-10-16 21:34:46 -0700231 hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
232 hellobuffer.append(" <capabilities>\n");
233 deviceCapabilities.forEach(
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800234 cap -> hellobuffer.append(" <capability>")
235 .append(cap)
236 .append("</capability>\n"));
andreaeb70a942015-10-16 21:34:46 -0700237 hellobuffer.append(" </capabilities>\n");
238 hellobuffer.append("</hello>\n");
Andrea Campanella101417d2015-12-11 17:58:07 -0800239 hellobuffer.append(ENDPATTERN);
andreaeb70a942015-10-16 21:34:46 -0700240 return hellobuffer.toString();
241
242 }
243
Andrea Campanella101417d2015-12-11 17:58:07 -0800244 private void checkAndRestablishSession() throws NetconfException {
Andrea Campanella1cd641b2015-12-07 17:28:34 -0800245 if (sshSession.getState() != 2) {
246 try {
247 startSshSession();
248 } catch (IOException e) {
Ryan Goulding69524392016-12-03 13:21:20 -0500249 log.debug("The connection with {} was reopened", deviceInfo.getDeviceId());
Andrea Campanella1cd641b2015-12-07 17:28:34 -0800250 try {
251 startConnection();
252 } catch (IOException e2) {
Andrea Campanella50d25212016-02-26 13:06:23 -0800253 log.error("No connection {} for device", netconfConnection, e2);
Andrea Campanella101417d2015-12-11 17:58:07 -0800254 throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e);
Andrea Campanella1cd641b2015-12-07 17:28:34 -0800255 }
256 }
257 }
258 }
259
andreaeb70a942015-10-16 21:34:46 -0700260 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800261 public String requestSync(String request) throws NetconfException {
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800262 if (!request.contains(ENDPATTERN)) {
263 request = request + NEW_LINE + ENDPATTERN;
264 }
265 String reply = sendRequest(request);
Andreas Papazois2e557be2016-06-04 15:39:56 +0300266 checkReply(reply);
267 return reply;
andreaeb70a942015-10-16 21:34:46 -0700268 }
269
270 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800271 public CompletableFuture<String> request(String request) {
helenyrwu0407c642016-06-09 12:01:30 -0700272 CompletableFuture<String> ftrep = streamHandler.sendMessage(request);
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800273 replies.put(messageIdInteger.get(), ftrep);
Andrea Campanella101417d2015-12-11 17:58:07 -0800274 return ftrep;
275 }
276
277 private String sendRequest(String request) throws NetconfException {
278 checkAndRestablishSession();
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800279 request = formatRequestMessageId(request);
280 request = formatXmlHeader(request);
Andrea Campanella101417d2015-12-11 17:58:07 -0800281 CompletableFuture<String> futureReply = request(request);
Andreas Papazoisd4712e22016-02-10 15:59:55 +0200282 messageIdInteger.incrementAndGet();
Andreas Papazois4752cfa2016-04-25 14:52:12 +0300283 int replyTimeout = NetconfControllerImpl.netconfReplyTimeout;
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800284 String rp;
285 try {
Andreas Papazois4752cfa2016-04-25 14:52:12 +0300286 rp = futureReply.get(replyTimeout, TimeUnit.SECONDS);
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800287 } catch (InterruptedException | ExecutionException | TimeoutException e) {
Andreas Papazoisd4712e22016-02-10 15:59:55 +0200288 throw new NetconfException("No matching reply for request " + request, e);
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800289 }
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800290 log.debug("Result {} from request {} to device {}", rp, request, deviceInfo);
Andrea Campanella50d25212016-02-26 13:06:23 -0800291 return rp.trim();
Andrea Campanella101417d2015-12-11 17:58:07 -0800292 }
293
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800294 private String formatRequestMessageId(String request) {
295 if (request.contains(MESSAGE_ID_STRING)) {
296 //FIXME if application provieds his own counting of messages this fails that count
297 request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER,
298 MESSAGE_ID_STRING + EQUAL + "\"" + messageIdInteger.get() + "\"");
299 } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) {
300 //FIXME find out a better way to enforce the presence of message-id
301 request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\""
302 + messageIdInteger.get() + "\"" + ">");
303 }
304 return request;
305 }
306
307 private String formatXmlHeader(String request) {
308 if (!request.contains(XML_HEADER)) {
309 //FIXME if application provieds his own XML header of different type there is a clash
310 request = XML_HEADER + "\n" + request;
311 }
312 return request;
313 }
314
Andrea Campanella101417d2015-12-11 17:58:07 -0800315 @Override
Akihiro Yamanouchi8d3a9d32016-07-12 11:41:44 +0900316 public String doWrappedRpc(String request) throws NetconfException {
317 StringBuilder rpc = new StringBuilder(XML_HEADER);
318 rpc.append(RPC_OPEN);
319 rpc.append(MESSAGE_ID_STRING);
320 rpc.append(EQUAL);
321 rpc.append("\"");
322 rpc.append(messageIdInteger.get());
323 rpc.append("\" ");
324 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
325 rpc.append(request);
326 rpc.append(RPC_CLOSE).append(NEW_LINE);
327 rpc.append(ENDPATTERN);
328 String reply = sendRequest(rpc.toString());
329 checkReply(reply);
330 return reply;
331 }
332
333 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800334 public String get(String request) throws NetconfException {
335 return requestSync(request);
336 }
337
338 @Override
Akihiro Yamanouchi5e5d4df2016-06-08 17:06:33 +0900339 public String get(String filterSchema, String withDefaultsMode) throws NetconfException {
340 StringBuilder rpc = new StringBuilder(XML_HEADER);
341 rpc.append(RPC_OPEN);
342 rpc.append(MESSAGE_ID_STRING);
343 rpc.append(EQUAL);
344 rpc.append("\"");
345 rpc.append(messageIdInteger.get());
346 rpc.append("\" ");
347 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
348 rpc.append(GET_OPEN).append(NEW_LINE);
349 if (filterSchema != null) {
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900350 rpc.append(SUBTREE_FILTER_OPEN).append(NEW_LINE);
Akihiro Yamanouchi5e5d4df2016-06-08 17:06:33 +0900351 rpc.append(filterSchema).append(NEW_LINE);
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900352 rpc.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE);
Akihiro Yamanouchi5e5d4df2016-06-08 17:06:33 +0900353 }
354 if (withDefaultsMode != null) {
355 rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">");
356 rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE);
357 }
358 rpc.append(GET_CLOSE).append(NEW_LINE);
359 rpc.append(RPC_CLOSE).append(NEW_LINE);
360 rpc.append(ENDPATTERN);
361 String reply = sendRequest(rpc.toString());
362 checkReply(reply);
363 return reply;
364 }
365
366 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800367 public String getConfig(String targetConfiguration) throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700368 return getConfig(targetConfiguration, null);
369 }
370
371 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800372 public String getConfig(String targetConfiguration, String configurationSchema) throws NetconfException {
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800373 StringBuilder rpc = new StringBuilder(XML_HEADER);
374 rpc.append("<rpc ");
375 rpc.append(MESSAGE_ID_STRING);
376 rpc.append(EQUAL);
377 rpc.append("\"");
378 rpc.append(messageIdInteger.get());
379 rpc.append("\" ");
380 rpc.append("xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
andreaeb70a942015-10-16 21:34:46 -0700381 rpc.append("<get-config>\n");
382 rpc.append("<source>\n");
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800383 rpc.append("<").append(targetConfiguration).append("/>");
andreaeb70a942015-10-16 21:34:46 -0700384 rpc.append("</source>");
385 if (configurationSchema != null) {
386 rpc.append("<filter type=\"subtree\">\n");
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800387 rpc.append(configurationSchema).append("\n");
andreaeb70a942015-10-16 21:34:46 -0700388 rpc.append("</filter>\n");
389 }
390 rpc.append("</get-config>\n");
391 rpc.append("</rpc>\n");
Andrea Campanella101417d2015-12-11 17:58:07 -0800392 rpc.append(ENDPATTERN);
393 String reply = sendRequest(rpc.toString());
Andrea Campanella1cd641b2015-12-07 17:28:34 -0800394 return checkReply(reply) ? reply : "ERROR " + reply;
andreaeb70a942015-10-16 21:34:46 -0700395 }
396
397 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800398 public boolean editConfig(String newConfiguration) throws NetconfException {
399 newConfiguration = newConfiguration + ENDPATTERN;
400 return checkReply(sendRequest(newConfiguration));
andreaeb70a942015-10-16 21:34:46 -0700401 }
402
403 @Override
Andrea Campanellaf4fd0352015-12-14 17:03:05 -0800404 public boolean editConfig(String targetConfiguration, String mode, String newConfiguration)
Andrea Campanella101417d2015-12-11 17:58:07 -0800405 throws NetconfException {
Andrea Campanellaf4fd0352015-12-14 17:03:05 -0800406 newConfiguration = newConfiguration.trim();
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800407 StringBuilder rpc = new StringBuilder(XML_HEADER);
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900408 rpc.append(RPC_OPEN);
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800409 rpc.append(MESSAGE_ID_STRING);
410 rpc.append(EQUAL);
411 rpc.append("\"");
412 rpc.append(messageIdInteger.get());
413 rpc.append("\" ");
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900414 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
415 rpc.append(EDIT_CONFIG_OPEN).append("\n");
416 rpc.append(TARGET_OPEN);
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800417 rpc.append("<").append(targetConfiguration).append("/>");
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900418 rpc.append(TARGET_CLOSE).append("\n");
419 if (mode != null) {
420 rpc.append(DEFAULT_OPERATION_OPEN);
421 rpc.append(mode);
422 rpc.append(DEFAULT_OPERATION_CLOSE).append("\n");
423 }
424 rpc.append(CONFIG_OPEN).append("\n");
Andrea Campanellaf4fd0352015-12-14 17:03:05 -0800425 rpc.append(newConfiguration);
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900426 rpc.append(CONFIG_CLOSE).append("\n");
427 rpc.append(EDIT_CONFIG_CLOSE).append("\n");
428 rpc.append(RPC_CLOSE);
Andrea Campanella101417d2015-12-11 17:58:07 -0800429 rpc.append(ENDPATTERN);
Konstantinos Kanonakis1b8b5592016-09-09 14:34:37 -0500430 log.debug(rpc.toString());
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900431 String reply = sendRequest(rpc.toString());
432 return checkReply(reply);
Andrea Campanellaf4fd0352015-12-14 17:03:05 -0800433 }
434
435 @Override
Andrea Campanella1cd641b2015-12-07 17:28:34 -0800436 public boolean copyConfig(String targetConfiguration, String newConfiguration)
Andrea Campanella101417d2015-12-11 17:58:07 -0800437 throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700438 newConfiguration = newConfiguration.trim();
yoonseona1957552016-11-02 15:53:07 -0400439 if (!newConfiguration.startsWith("<config>")) {
440 newConfiguration = "<config>" + newConfiguration
441 + "</config>";
andreaeb70a942015-10-16 21:34:46 -0700442 }
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800443 StringBuilder rpc = new StringBuilder(XML_HEADER);
yoonseon55faf852016-11-02 14:59:12 -0400444 rpc.append(RPC_OPEN);
445 rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
andreaeb70a942015-10-16 21:34:46 -0700446 rpc.append("<copy-config>");
447 rpc.append("<target>");
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800448 rpc.append("<").append(targetConfiguration).append("/>");
andreaeb70a942015-10-16 21:34:46 -0700449 rpc.append("</target>");
450 rpc.append("<source>");
yoonseon25e54fc2016-11-02 13:07:43 -0400451 rpc.append(newConfiguration);
andreaeb70a942015-10-16 21:34:46 -0700452 rpc.append("</source>");
453 rpc.append("</copy-config>");
454 rpc.append("</rpc>");
Andrea Campanella101417d2015-12-11 17:58:07 -0800455 rpc.append(ENDPATTERN);
456 return checkReply(sendRequest(rpc.toString()));
andreaeb70a942015-10-16 21:34:46 -0700457 }
458
459 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800460 public boolean deleteConfig(String targetConfiguration) throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700461 if (targetConfiguration.equals("running")) {
462 log.warn("Target configuration for delete operation can't be \"running\"",
463 targetConfiguration);
464 return false;
465 }
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800466 StringBuilder rpc = new StringBuilder(XML_HEADER);
andreaeb70a942015-10-16 21:34:46 -0700467 rpc.append("<rpc>");
468 rpc.append("<delete-config>");
469 rpc.append("<target>");
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800470 rpc.append("<").append(targetConfiguration).append("/>");
andreaeb70a942015-10-16 21:34:46 -0700471 rpc.append("</target>");
472 rpc.append("</delete-config>");
473 rpc.append("</rpc>");
Andrea Campanella101417d2015-12-11 17:58:07 -0800474 rpc.append(ENDPATTERN);
475 return checkReply(sendRequest(rpc.toString()));
andreaeb70a942015-10-16 21:34:46 -0700476 }
477
478 @Override
helenyrwu0407c642016-06-09 12:01:30 -0700479 public boolean lock(String configType) throws NetconfException {
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800480 StringBuilder rpc = new StringBuilder(XML_HEADER);
helenyrwu0407c642016-06-09 12:01:30 -0700481 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
andreaeb70a942015-10-16 21:34:46 -0700482 rpc.append("<lock>");
483 rpc.append("<target>");
helenyrwu0407c642016-06-09 12:01:30 -0700484 rpc.append("<");
485 rpc.append(configType);
486 rpc.append("/>");
andreaeb70a942015-10-16 21:34:46 -0700487 rpc.append("</target>");
488 rpc.append("</lock>");
489 rpc.append("</rpc>");
Andrea Campanella101417d2015-12-11 17:58:07 -0800490 rpc.append(ENDPATTERN);
helenyrwu0407c642016-06-09 12:01:30 -0700491 String lockReply = sendRequest(rpc.toString());
492 return checkReply(lockReply);
andreaeb70a942015-10-16 21:34:46 -0700493 }
494
495 @Override
helenyrwu0407c642016-06-09 12:01:30 -0700496 public boolean unlock(String configType) throws NetconfException {
Andrea Campanellab029b9e2016-01-29 11:05:36 -0800497 StringBuilder rpc = new StringBuilder(XML_HEADER);
helenyrwu0407c642016-06-09 12:01:30 -0700498 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n");
andreaeb70a942015-10-16 21:34:46 -0700499 rpc.append("<unlock>");
500 rpc.append("<target>");
helenyrwu0407c642016-06-09 12:01:30 -0700501 rpc.append("<");
502 rpc.append(configType);
503 rpc.append("/>");
andreaeb70a942015-10-16 21:34:46 -0700504 rpc.append("</target>");
505 rpc.append("</unlock>");
506 rpc.append("</rpc>");
Andrea Campanella101417d2015-12-11 17:58:07 -0800507 rpc.append(ENDPATTERN);
helenyrwu0407c642016-06-09 12:01:30 -0700508 String unlockReply = sendRequest(rpc.toString());
509 return checkReply(unlockReply);
510 }
511
512 @Override
513 public boolean lock() throws NetconfException {
514 return lock("running");
515 }
516
517 @Override
518 public boolean unlock() throws NetconfException {
519 return unlock("running");
andreaeb70a942015-10-16 21:34:46 -0700520 }
521
522 @Override
Andrea Campanella101417d2015-12-11 17:58:07 -0800523 public boolean close() throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700524 return close(false);
525 }
526
Andrea Campanella101417d2015-12-11 17:58:07 -0800527 private boolean close(boolean force) throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700528 StringBuilder rpc = new StringBuilder();
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700529 rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">");
andreaeb70a942015-10-16 21:34:46 -0700530 if (force) {
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700531 rpc.append("<kill-session/>");
andreaeb70a942015-10-16 21:34:46 -0700532 } else {
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700533 rpc.append("<close-session/>");
andreaeb70a942015-10-16 21:34:46 -0700534 }
andreaeb70a942015-10-16 21:34:46 -0700535 rpc.append("</rpc>");
Andrea Campanella101417d2015-12-11 17:58:07 -0800536 rpc.append(ENDPATTERN);
537 return checkReply(sendRequest(rpc.toString())) || close(true);
andreaeb70a942015-10-16 21:34:46 -0700538 }
539
540 @Override
541 public String getSessionId() {
542 if (serverCapabilities.contains("<session-id>")) {
543 String[] outer = serverCapabilities.split("<session-id>");
544 Preconditions.checkArgument(outer.length != 1,
545 "Error in retrieving the session id");
546 String[] value = outer[1].split("</session-id>");
547 Preconditions.checkArgument(value.length != 1,
548 "Error in retrieving the session id");
549 return value[0];
550 } else {
551 return String.valueOf(-1);
552 }
553 }
554
555 @Override
556 public String getServerCapabilities() {
557 return serverCapabilities;
558 }
559
560 @Override
561 public void setDeviceCapabilities(List<String> capabilities) {
562 deviceCapabilities = capabilities;
563 }
564
Andrea Campanella101417d2015-12-11 17:58:07 -0800565 @Override
566 public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
helenyrwu0407c642016-06-09 12:01:30 -0700567 streamHandler.addDeviceEventListener(listener);
Andrea Campanella101417d2015-12-11 17:58:07 -0800568 }
569
570 @Override
571 public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) {
helenyrwu0407c642016-06-09 12:01:30 -0700572 streamHandler.removeDeviceEventListener(listener);
Andrea Campanella101417d2015-12-11 17:58:07 -0800573 }
574
575 private boolean checkReply(String reply) throws NetconfException {
andreaeb70a942015-10-16 21:34:46 -0700576 if (reply != null) {
577 if (!reply.contains("<rpc-error>")) {
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900578 log.debug("Device {} sent reply {}", deviceInfo, reply);
andreaeb70a942015-10-16 21:34:46 -0700579 return true;
580 } else if (reply.contains("<ok/>")
581 || (reply.contains("<rpc-error>")
582 && reply.contains("warning"))) {
Akihiro Yamanouchid4912842016-07-01 10:38:46 +0900583 log.debug("Device {} sent reply {}", deviceInfo, reply);
andreaeb70a942015-10-16 21:34:46 -0700584 return true;
585 }
586 }
Andrea Campanellad264b492016-03-01 09:46:06 -0800587 log.warn("Device {} has error in reply {}", deviceInfo, reply);
andreaeb70a942015-10-16 21:34:46 -0700588 return false;
589 }
590
Andrea Campanella101417d2015-12-11 17:58:07 -0800591 public class NetconfSessionDelegateImpl implements NetconfSessionDelegate {
andreaeb70a942015-10-16 21:34:46 -0700592
Andrea Campanella101417d2015-12-11 17:58:07 -0800593 @Override
Andreas Papazoisd4712e22016-02-10 15:59:55 +0200594 public void notify(NetconfDeviceOutputEvent event) {
595 Optional<Integer> messageId = event.getMessageID();
helenyrwu0407c642016-06-09 12:01:30 -0700596
Andreas Papazoisd4712e22016-02-10 15:59:55 +0200597 if (!messageId.isPresent()) {
598 errorReplies.add(event.getMessagePayload());
Andrea Campanellad264b492016-03-01 09:46:06 -0800599 log.error("Device {} sent error reply {}",
600 event.getDeviceInfo(), event.getMessagePayload());
Andreas Papazoisd4712e22016-02-10 15:59:55 +0200601 return;
602 }
603 CompletableFuture<String> completedReply =
604 replies.get(messageId.get());
Akihiro Yamanouchi45122222016-07-15 13:13:11 +0900605 if (completedReply != null) {
606 completedReply.complete(event.getMessagePayload());
607 }
andreaeb70a942015-10-16 21:34:46 -0700608 }
609 }
andreaeb70a942015-10-16 21:34:46 -0700610}