-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathNetconfSession.java
More file actions
1694 lines (1550 loc) · 66.6 KB
/
NetconfSession.java
File metadata and controls
1694 lines (1550 loc) · 66.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2013 Juniper Networks, Inc.
All Rights Reserved
Use is subject to license terms.
*/
package net.juniper.netconf;
import com.google.common.annotations.VisibleForTesting;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSchException;
import net.juniper.netconf.element.Datastore;
import net.juniper.netconf.element.Hello;
import net.juniper.netconf.element.RpcReply;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.ByteArrayOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A {@code NetconfSession} is obtained by first building a
* {@link Device} and then calling {@link Device#connect()}.
* <p>
* Typically, one
* <ol>
* <li>Build a {@link Device} using its fluent {@code builder()}.</li>
* <li>Invoke {@link Device#connect()} to establish transport and receive a
* {@code NetconfSession}.</li>
* <li>Perform RPC operations via the session
* (e.g. {@link #executeRPC(String)}, {@link #killSession(String)},
* {@link #commitConfirm(long, String)}, {@link #cancelCommit(String)}).</li>
* <li>Call {@link #close()} when finished to free resources.</li>
* </ol>
* <p>
* A {@code NetconfSession} should be treated as a single-threaded conversation
* with the server. The library supports sequential reuse of one session across
* multiple RPCs, but does not guarantee safety for multiple concurrent
* in-flight RPCs on the same session. Use separate NETCONF sessions when
* application-level concurrency is required.
*/
public class NetconfSession {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(NetconfSession.class);
private final Channel netconfChannel;
private String serverCapability;
private Hello serverHello;
private final InputStream stdInStreamFromDevice;
private final OutputStream stdOutStreamToDevice;
private String lastRpcReply;
private RpcReply lastRpcReplyObject;
private final DocumentBuilder builder;
private final int commandTimeout;
private final Map<String, String> rpcAttrMap = new HashMap<>();
private String rpcAttributes;
private int messageId = 0;
/**
* Size (in characters) of the temporary read buffer used when collecting
* RPC replies from the device. Set larger than the internal buffer in
* {@link java.io.BufferedReader} so that large replies are less likely to
* require multiple passes.
*/
public static final int BUFFER_SIZE = 9 * 1024;
private static final String CANDIDATE_CONFIG = "candidate";
private static final String EMPTY_CONFIGURATION_TAG = "<configuration></configuration>";
private static final String RUNNING_CONFIG = "running";
private static final String NETCONF_SYNTAX_ERROR_MSG_FROM_DEVICE = "netconf error: syntax error";
private static final byte[] DEVICE_PROMPT_BYTES = NetconfConstants.DEVICE_PROMPT.getBytes(StandardCharsets.UTF_8);
private static final Pattern RPC_START_TAG_PATTERN = Pattern.compile("^<rpc\\b([^>]*)>", Pattern.DOTALL);
private static final Pattern MESSAGE_ID_ATTRIBUTE_PATTERN =
Pattern.compile("\\bmessage-id\\s*=\\s*(['\"])(.*?)\\1", Pattern.DOTALL);
private static final Pattern XML_DECLARATION_PATTERN =
Pattern.compile("^<\\?xml[^>]*\\?>\\s*", Pattern.DOTALL);
private final List<String> clientCapabilities;
private boolean useChunkedFraming;
private NegotiatedCapabilities negotiatedCapabilities;
private byte[] unreadBytes = new byte[0];
private record PreparedRpc(String xml, String messageId) { }
NetconfSession(Channel netconfChannel, int timeout, String hello,
DocumentBuilder builder) throws IOException {
this(netconfChannel, timeout, timeout, defaultClientCapabilities(), hello, builder);
}
NetconfSession(Channel netconfChannel, int connectionTimeout, int commandTimeout,
String hello,
DocumentBuilder builder) throws IOException {
this(netconfChannel, connectionTimeout, commandTimeout, defaultClientCapabilities(), hello, builder);
}
NetconfSession(Channel netconfChannel, int timeout, List<String> clientCapabilities,
String hello, DocumentBuilder builder) throws IOException {
this(netconfChannel, timeout, timeout, clientCapabilities, hello, builder);
}
NetconfSession(Channel netconfChannel, int connectionTimeout, int commandTimeout,
List<String> clientCapabilities,
String hello,
DocumentBuilder builder) throws IOException {
stdInStreamFromDevice = netconfChannel.getInputStream();
stdOutStreamToDevice = netconfChannel.getOutputStream();
try {
netconfChannel.connect(connectionTimeout);
} catch (JSchException e) {
throw new NetconfException("Failed to create Netconf session:" +
e.getMessage(), e);
}
this.netconfChannel = netconfChannel;
this.commandTimeout = commandTimeout;
this.builder = builder;
this.clientCapabilities = clientCapabilities == null ? List.of() : List.copyOf(clientCapabilities);
sendHello(hello);
}
private static List<String> defaultClientCapabilities() {
return List.of(
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1
);
}
private XML convertToXML(String xml) throws SAXException, IOException {
if (xml.contains(NETCONF_SYNTAX_ERROR_MSG_FROM_DEVICE)) {
throw new NetconfException(String.format("Netconf server detected an error: %s", xml));
}
Document doc = builder.parse(new InputSource(new StringReader(xml)));
Element root = doc.getDocumentElement();
return new XML(root);
}
private void sendHello(String hello) throws IOException {
setHelloReply(getRpcReply(hello));
}
@VisibleForTesting
String getRpcReply(String rpc) throws IOException {
PreparedRpc preparedRpc = sendRpcRequest(rpc);
String reply;
if (useChunkedFraming) {
reply = readChunkedRpcReply();
} else {
reply = readLegacyRpcReply();
}
validateReplyMessageId(preparedRpc.messageId(), reply);
return reply;
}
private String readLegacyRpcReply() throws IOException {
final byte[] buffer = new byte[BUFFER_SIZE];
final ByteArrayOutputStream rpcReply = new ByteArrayOutputStream();
final long startTime = System.nanoTime();
boolean timeoutNotExceeded = true;
int promptPosition = -1;
while (promptPosition < 0 &&
(timeoutNotExceeded = !commandTimedOut(startTime))) {
int bytesRead = readIncomingBytes(buffer);
if (bytesRead < 0) {
throw new NetconfException("Input Stream has been closed during reading.");
}
rpcReply.write(buffer, 0, bytesRead);
byte[] rpcReplyBytes = rpcReply.toByteArray();
promptPosition = indexOf(rpcReplyBytes, DEVICE_PROMPT_BYTES);
if (promptPosition >= 0) {
int unreadStart = promptPosition + DEVICE_PROMPT_BYTES.length;
if (unreadStart < rpcReplyBytes.length) {
pushBackBytes(Arrays.copyOfRange(rpcReplyBytes, unreadStart, rpcReplyBytes.length));
}
String reply = new String(rpcReplyBytes, 0, promptPosition, StandardCharsets.UTF_8);
log.debug("Received Netconf RPC-Reply\n{}", reply);
return reply;
}
}
throw new SocketTimeoutException("Command timeout limit was exceeded: " + commandTimeout);
}
private String readChunkedRpcReply() throws IOException {
final long startTime = System.nanoTime();
final ByteArrayOutputStream rpcReply = new ByteArrayOutputStream();
while (!commandTimedOut(startTime)) {
String header = readChunkHeaderLine(startTime);
if (header.isEmpty()) {
continue;
}
if ("##".equals(header)) {
String reply = rpcReply.toString(StandardCharsets.UTF_8);
log.debug("Received Netconf RPC-Reply\n{}", reply);
return reply;
}
if (!header.startsWith("#")) {
throw new NetconfException("Invalid NETCONF chunked framing header: " + header);
}
int chunkSize;
try {
chunkSize = Integer.parseInt(header.substring(1));
} catch (NumberFormatException e) {
throw new NetconfException("Invalid NETCONF chunk size: " + header, e);
}
if (chunkSize < 0) {
throw new NetconfException("Invalid NETCONF chunk size: " + header);
}
rpcReply.write(readExactBytes(chunkSize, startTime));
}
throw new SocketTimeoutException("Command timeout limit was exceeded: " + commandTimeout);
}
private BufferedReader getRpcReplyRunning(String rpc) throws IOException {
sendRpcRequest(rpc);
return new BufferedReader(
new InputStreamReader(createRpcReplyInputStream(), StandardCharsets.UTF_8));
}
private InputStream createRpcReplyInputStream() {
return useChunkedFraming ? new ChunkedRpcReplyInputStream() : new LegacyRpcReplyInputStream();
}
private PreparedRpc sendRpcRequest(String rpc) throws IOException {
PreparedRpc preparedRpc = prepareRpcRequest(rpc);
log.debug("Sending Netconf RPC\n{}", preparedRpc.xml());
stdOutStreamToDevice.write(applyTransportFraming(preparedRpc.xml()));
stdOutStreamToDevice.flush();
return preparedRpc;
}
private PreparedRpc prepareRpcRequest(String rpc) {
String normalizedRpc = stripLegacyEndOfMessage(rpc).trim();
String expectedMessageId = null;
if (isHelloMessage(normalizedRpc)) {
return new PreparedRpc(addXmlDeclarationIfMissing(normalizedRpc), null);
}
if (isRpcEnvelope(normalizedRpc)) {
messageId++;
expectedMessageId = extractRpcMessageId(normalizedRpc);
if (expectedMessageId == null) {
expectedMessageId = String.valueOf(messageId);
normalizedRpc = injectMessageId(normalizedRpc, expectedMessageId);
}
}
normalizedRpc = normalizedRpc.replace("<datastore>", "<datastore xmlns:ds=\"urn:ietf:params:xml:ns:yang:ietf-datastores\">");
normalizedRpc = normalizedRpc.replace("<get-data>", "<get-data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-nmda\">");
return new PreparedRpc(addXmlDeclarationIfMissing(normalizedRpc), expectedMessageId);
}
/**
* Gets the current rpc attribute string. If the rpc attribute string is not yet generated or has been reset then
* we generate rpc attributes from the RPC Attribute Map.
*
* @return The attribute set XML formatted into a string.
*/
public String getRpcAttributes() {
if(rpcAttributes == null) {
StringBuilder attributes = new StringBuilder();
boolean useDefaultNamespace = true;
for (Map.Entry<String, String> attribute : rpcAttrMap.entrySet()) {
attributes.append(String.format(" %1s=\"%2s\"", attribute.getKey(), attribute.getValue()));
if ("xmlns".equals(attribute.getKey()))
useDefaultNamespace = false;
}
if (useDefaultNamespace)
attributes.append(" xmlns=\"" + NetconfConstants.URN_XML_NS_NETCONF_BASE_1_0 + "\"");
rpcAttributes = attributes.toString();
}
return rpcAttributes;
}
/**
* Loads the candidate configuration, Configuration should be in XML format.
*
* @param configuration Configuration,in XML format, to be loaded. For example,
* "<configuration><system><services><ftp/><
* services/></system></configuration/>"
* will load 'ftp' under the 'systems services' hierarchy.
* @param loadType You can choose "merge" or "replace" as the loadType.
* @throws org.xml.sax.SAXException If there are issues parsing the config file.
* @throws java.io.IOException If there are issues reading the config file.
*/
public void loadXMLConfiguration(String configuration, String loadType) throws IOException, SAXException {
requireCandidateCapability("loadXMLConfiguration");
validateLoadType(loadType);
configuration = configuration.trim();
if (!configuration.startsWith("<configuration")) {
configuration = "<configuration>" + configuration
+ "</configuration>";
}
String rpc = "<rpc>" +
"<edit-config>" +
"<target>" +
"<" + CANDIDATE_CONFIG + "/>" +
"</target>" +
"<default-operation>" +
loadType +
"</default-operation>" +
"<config>" +
configuration +
"</config>" +
"</edit-config>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
try {
setLastRpcReply(getRpcReply(rpc));
} catch (NetconfException e) {
// Propagate as a LoadException so the caller knows this happened
throw new LoadException("Load operation returned error.", e);
}
if (hasError() || !isOK()) {
throw new LoadException(
RpcErrorException.buildMessage("Load operation", lastRpcReplyObject),
lastRpcReplyObject
);
}
}
private void setHelloReply(final String reply) throws IOException {
this.serverCapability = reply;
this.lastRpcReply = reply;
try {
this.serverHello = Hello.from(reply);
this.negotiatedCapabilities =
NegotiatedCapabilities.fromCapabilities(clientCapabilities, serverHello.getCapabilities());
this.useChunkedFraming = negotiatedCapabilities.usesChunkedFraming();
} catch (final ParserConfigurationException | SAXException | XPathExpressionException e) {
throw new NetconfException("Invalid <hello> message from server: " + reply, e);
}
}
private void setLastRpcReply(final String reply) throws IOException {
this.lastRpcReply = reply;
try {
this.lastRpcReplyObject = RpcReply.from(reply);
} catch (final ParserConfigurationException | SAXException | XPathExpressionException e) {
throw new NetconfException("Invalid <rpc-reply> message from server: " + lastRpcReply, e);
}
}
/**
* Loads the candidate configuration, Configuration should be in text/tree
* format.
*
* @param configuration Configuration,in text/tree format, to be loaded. For example,
* "system {
* services {
* ftp;
* }
* }"
* will load 'ftp' under the 'systems services' hierarchy.
* @param loadType You can choose "merge" or "replace" as the loadType.
* @throws org.xml.sax.SAXException If there are issues parsing the config file.
* @throws java.io.IOException If there are issues reading the config file.
*/
public void loadTextConfiguration(String configuration, String loadType) throws IOException, SAXException {
requireCandidateCapability("loadTextConfiguration");
String rpc = "<rpc>" +
"<edit-config>" +
"<target>" +
"<" + CANDIDATE_CONFIG + "/>" +
"</target>" +
"<default-operation>" +
loadType +
"</default-operation>" +
"<config-text>" +
"<configuration-text>" +
configuration +
"</configuration-text>" +
"</config-text>" +
"</edit-config>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
try {
setLastRpcReply(getRpcReply(rpc));
} catch (NetconfException e) {
throw new LoadException("Load operation returned error.", e);
}
if (hasError() || !isOK()) {
throw new LoadException(
RpcErrorException.buildMessage("Load operation", lastRpcReplyObject),
lastRpcReplyObject
);
}
}
private String getConfig(String configTree) throws IOException {
requireCandidateCapability("getCandidateConfig");
String rpc = "<rpc>" +
"<get-config>" +
"<source>" +
"<" + CANDIDATE_CONFIG + "/>" +
"</source>" +
"<filter type=\"subtree\">" +
configTree +
"</filter>" +
"</get-config>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
return lastRpcReply;
}
/**
* Executes a NETCONF {@code <get>} operation against the device’s running
* datastore and returns the configuration **and** operational state data.
*
* @param xpathFilter optional XPath filter to limit the returned subtree;
* pass {@code null} to retrieve the entire running state
* @return an {@link XML} object representing the server’s {@code <rpc-reply>}
* @throws IOException if communication with the device fails
* @throws SAXException if the reply cannot be parsed into valid XML
*/
public XML getRunningConfigAndState(String xpathFilter) throws IOException, SAXException {
String rpc = "<rpc>" +
"<get>" +
(xpathFilter == null ? "" : xpathFilter) +
"</get>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
return convertToXML(lastRpcReply);
}
/**
* Executes the YANG NMDA {@code <get-data>} operation against the specified
* {@link Datastore}.
*
* @param xpathFilter optional XPath filter that narrows the returned data;
* may be {@code null} for an unfiltered request
* @param datastore the target datastore (e.g., {@code operational}, {@code running});
* must not be {@code null}
* @return an {@link XML} object containing the server’s reply
* @throws IllegalArgumentException if {@code datastore} is {@code null}
* @throws IOException if communication with the device fails
* @throws SAXException if the reply XML is malformed
*/
public XML getData(String xpathFilter, Datastore datastore)
throws IOException, SAXException {
if (datastore == null) {
throw new IllegalArgumentException("Datastore argument must not be null");
}
String rpc = "<rpc>" +
"<get-data>" +
"<datastore>ds:" + datastore + "</datastore>" +
(xpathFilter == null ? "" : xpathFilter) +
"</get-data>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
lastRpcReply = getRpcReply(rpc);
return convertToXML(lastRpcReply);
}
private String getConfig(String target, String configTree)
throws IOException {
String rpc = "<rpc>" +
"<get-config>" +
"<source>" +
"<" + target + "/>" +
"</source>" +
(configTree == null ? "" : "<filter type=\"subtree\">" + configTree + "</filter>") +
"</get-config>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
return lastRpcReply;
}
/**
* Get capability of the Netconf server.
*
* @return server capability
*/
public String getServerCapability() {
return serverCapability;
}
/**
* Returns the <hello> message received from the server.
* See <a href="https://datatracker.ietf.org/doc/html/rfc6241#section-8.1">...</a>
* @return the <hello> message received from the server.
*/
public Hello getServerHello() {
return serverHello;
}
/**
* Returns the negotiated capability view for this session.
*
* @return immutable capability snapshot
*/
public NegotiatedCapabilities getNegotiatedCapabilities() {
return negotiatedCapabilities;
}
/**
* Sends a raw RPC string, waits for the {@code <rpc-reply>}, and converts the
* response to an {@link XML} object.
* <p>
* If the server includes any {@code <rpc-error>} elements, the call
* throws a {@link RpcErrorException}. This makes error handling
* symmetrical with other high‑level helpers (e.g. {@code load*()},
* {@code commit()}).
*
* @param rpcContent the RPC payload (with or without <rpc> wrapper)
* @return parsed {@link XML} representation of the reply
* @throws RpcErrorException if the reply contains one or more
* {@code <rpc-error>} elements
* @throws SAXException if the reply cannot be parsed as XML
* @throws IOException on transport errors
*/
public XML executeRPC(String rpcContent) throws SAXException, IOException {
String rpcReply = getRpcReply(fixupRpc(rpcContent));
setLastRpcReply(rpcReply);
if (hasError()) {
throw new RpcErrorException(
RpcErrorException.buildMessage("RPC execution", lastRpcReplyObject),
lastRpcReplyObject
);
}
return convertToXML(rpcReply);
}
/**
* Send an RPC (as XML object) over the Netconf session and get the response
* as an XML object.
*
* @param rpc RPC to be sent. Use the XMLBuilder to create RPC as an
* XML object.
* @return RPC reply sent by Netconf server
* @throws org.xml.sax.SAXException If the XML Reply cannot be parsed.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public XML executeRPC(XML rpc) throws SAXException, IOException {
return executeRPC(rpc.toString());
}
/**
* Send an RPC (as Document object) over the Netconf session and get the
* response as an XML object.
*
* @param rpcDoc RPC content to be sent, as a org.w3c.dom.Document object.
* @return RPC reply sent by Netconf server
* @throws org.xml.sax.SAXException If the XML Reply cannot be parsed.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public XML executeRPC(Document rpcDoc) throws SAXException, IOException {
Element root = rpcDoc.getDocumentElement();
XML xml = new XML(root);
return executeRPC(xml);
}
/**
* Given an RPC command, wrap it in RPC tags.
* <a href="https://tools.ietf.org/html/rfc6241#section-4.1">...</a>
*
* @param rpcContent an RPC command that may or may not be wrapped in < or >
* @return a string of the RPC command wrapped in <rpc>< ></rpc>
* @throws IllegalArgumentException if null is passed in as the rpcContent.
*/
@VisibleForTesting
static String fixupRpc(String rpcContent) throws IllegalArgumentException {
if (rpcContent == null) {
throw new IllegalArgumentException("Null RPC");
}
String trimmedRpcContent = rpcContent.trim();
if (isRpcEnvelope(trimmedRpcContent)) {
return rpcContent + NetconfConstants.DEVICE_PROMPT;
}
if (trimmedRpcContent.startsWith("<"))
rpcContent = "<rpc>" + trimmedRpcContent + "</rpc>";
else
rpcContent = "<rpc>" + "<" + trimmedRpcContent + "/>" + "</rpc>";
return rpcContent + NetconfConstants.DEVICE_PROMPT;
}
/**
* Send an RPC (as String object) over the default Netconf session and get
* the response as a BufferedReader.
*
* @param rpcContent RPC content to be sent. For example, to send an rpc
* <rpc><get-chassis-inventory/></rpc>, the
* String to be passed can be
* "<get-chassis-inventory/>" OR
* "get-chassis-inventory" OR
* "<rpc><get-chassis-inventory/></rpc>"
* @return RPC reply sent by Netconf server as a BufferedReader. This is
* useful if we want continuous stream of output, rather than wait
* for whole output till command execution completes.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public BufferedReader executeRPCRunning(String rpcContent) throws IOException {
return getRpcReplyRunning(fixupRpc(rpcContent));
}
/**
* Send an RPC (as XML object) over the Netconf session and get the response
* as a BufferedReader.
*
* @param rpc RPC to be sent. Use the XMLBuilder to create RPC as an
* XML object.
* @return RPC reply sent by Netconf server as a BufferedReader. This is
* useful if we want continuous stream of output, rather than wait
* for whole output till command execution completes.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public BufferedReader executeRPCRunning(XML rpc) throws IOException {
return executeRPCRunning(rpc.toString());
}
/**
* Send an RPC (as Document object) over the Netconf session and get the
* response as a BufferedReader.
*
* @param rpcDoc RPC content to be sent, as a org.w3c.dom.Document object.
* @return RPC reply sent by Netconf server as a BufferedReader. This is
* useful if we want continuous stream of output, rather than wait
* for whole output till command execution completes.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public BufferedReader executeRPCRunning(Document rpcDoc) throws IOException {
Element root = rpcDoc.getDocumentElement();
XML xml = new XML(root);
return executeRPCRunning(xml);
}
/**
* Get the session ID of the Netconf session.
*
* @return Session ID as a string.
*/
public String getSessionId() {
return serverHello.getSessionId();
}
/**
* Close the Netconf session. You should always call this once you don't
* need the session anymore.
*
* @throws IOException if there are errors communicating with the Device
*/
public void close() throws IOException {
String rpc = "<rpc>" +
"<close-session/>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
netconfChannel.disconnect();
}
/**
* Check if the last RPC reply returned from Netconf server has any error.
*
* @return true if any errors are found in last RPC reply.
*/
public boolean hasError() {
return lastRpcReplyObject.hasErrors();
}
/**
* Check if the last RPC reply returned from Netconf server has any warning.
*
* @return true if any errors are found in last RPC reply.
*/
public boolean hasWarning() {
return lastRpcReplyObject.hasWarnings();
}
/**
* Check if the last RPC reply returned from Netconf server,
* contains <ok/> tag.
*
* @return true if <ok/> tag is found in last RPC reply.
*/
public boolean isOK() {
return lastRpcReplyObject.isOK();
}
/**
* Locks the candidate configuration.
*
* @return true if successful.
* @throws org.xml.sax.SAXException If the XML Reply cannot be parsed.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public boolean lockConfig() throws IOException, SAXException {
requireCandidateCapability("lockConfig");
String rpc = "<rpc>" +
"<lock>" +
"<target>" +
"<candidate/>" +
"</target>" +
"</lock>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
return !hasError() && isOK();
}
/**
* Unlocks the candidate configuration.
*
* @return true if successful.
* @throws java.io.IOException If there are issues communicating with the netconf server.
*/
public boolean unlockConfig() throws IOException {
requireCandidateCapability("unlockConfig");
String rpc = "<rpc>" +
"<unlock>" +
"<target>" +
"<candidate/>" +
"</target>" +
"</unlock>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
return !hasError() && isOK();
}
/**
* Terminates another active NETCONF session on the server
* (<a href="https://datatracker.ietf.org/doc/html/rfc6241#section-7.9">RFC 6241 §7.9</a>).
* <p>
* The server will abort any operations in progress for that session,
* release resources and locks, and close the connection.
*
* @param sessionId the session identifier to terminate; must not be {@code null} or empty
* @return {@code true} if the operation succeeded (no <rpc-error> and an <ok/> was returned)
* @throws IllegalArgumentException if {@code sessionId} is {@code null} or empty
* @throws IOException if communication with the device fails
* @throws SAXException if the reply cannot be parsed
*/
public boolean killSession(String sessionId) throws IOException, SAXException {
if (sessionId == null || sessionId.isEmpty()) {
throw new IllegalArgumentException("sessionId must not be null or empty");
}
String rpc = "<rpc>" +
"<kill-session>" +
"<session-id>" + sessionId + "</session-id>" +
"</kill-session>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
return !hasError() && isOK();
}
/**
* Loads the candidate configuration, Configuration should be in set
* format.
* NOTE: This method is applicable only for JUNOS release 11.4 and above.
*
* @param configuration Configuration,in set format, to be loaded. For example,
* "set system services ftp"
* will load 'ftp' under the 'systems services' hierarchy.
* To load multiple set statements, separate them by '\n' character.
* @throws java.io.IOException If there are issues reading the config file.
*/
public void loadSetConfiguration(String configuration) throws IOException {
requireCandidateCapability("loadSetConfiguration");
String rpc = "<rpc>" +
"<load-configuration action=\"set\">" +
"<configuration-set>" +
configuration +
"</configuration-set>" +
"</load-configuration>" +
"</rpc>";
setLastRpcReply(getRpcReply(rpc));
if (hasError() || !isOK()) {
throw new LoadException(
RpcErrorException.buildMessage("Load operation", lastRpcReplyObject),
lastRpcReplyObject
);
}
}
/**
* Loads the candidate configuration from file,
* configuration should be in XML format.
*
* @param configFile Path name of file containing configuration,in xml format,
* to be loaded.
* @param loadType You can choose "merge" or "replace" as the loadType.
* @throws org.xml.sax.SAXException If there are issues parsing the config file.
* @throws java.io.IOException If there are issues reading the config file.
*/
public void loadXMLFile(String configFile, String loadType) throws IOException, SAXException {
requireCandidateCapability("loadXMLFile");
validateLoadType(loadType);
loadXMLConfiguration(readConfigFile(configFile), loadType);
}
/**
* Validate that the load type is either merge or replace.
*
* @param loadType how to load the config, merge or replace.
* @throws IllegalArgumentException if the load type is not merge or replace.
*/
private void validateLoadType(String loadType) throws IllegalArgumentException {
if (loadType == null || (!loadType.equals("merge") &&
!loadType.equals("replace")))
throw new IllegalArgumentException("'loadType' argument must be " +
"merge|replace");
}
/**
* Read the config file and return as a string.
*
* @param configFile The name of the configuration file
* @return a string of the config file.
* @throws java.io.IOException If there are issues reading the config file.
*/
private String readConfigFile(String configFile) throws IOException {
try {
return Files.readString(Paths.get(configFile), Charset.defaultCharset());
} catch (FileNotFoundException e) {
throw new FileNotFoundException("The system cannot find the configuration file specified: " + configFile);
}
}
/**
* Loads the candidate configuration from file,
* configuration should be in text/tree format.
*
* @param configFile Path name of file containing configuration,in xml format,
* to be loaded.
* @param loadType You can choose "merge" or "replace" as the loadType.
* @throws org.xml.sax.SAXException If there are issues parsing the config file.
* @throws java.io.IOException If there are issues reading the config file.
*/
public void loadTextFile(String configFile, String loadType) throws IOException, SAXException {
requireCandidateCapability("loadTextFile");
validateLoadType(loadType);
loadTextConfiguration(readConfigFile(configFile), loadType);
}
/**
* Loads the candidate configuration from file,
* configuration should be in set format.
* NOTE: This method is applicable only for JUNOS release 11.4 and above.
*
* @param configFile Path name of file containing configuration,in set format,
* to be loaded.
* @throws java.io.IOException If there are issues reading the config file.
*/
public void loadSetFile(String configFile) throws
IOException {
requireCandidateCapability("loadSetFile");
loadSetConfiguration(readConfigFile(configFile));
}
/**
* Loads and commits the candidate configuration, Configuration can be in
* text/xml/set format.
*
* @param configFile Path name of file containing configuration,in text/xml/set format,
* to be loaded. For example,
* "system {
* services {
* ftp;
* }
* }"
* will load 'ftp' under the 'systems services' hierarchy.
* OR
* "<configuration><system><services><ftp/><
* services/></system></configuration/>"
* will load 'ftp' under the 'systems services' hierarchy.
* OR
* "set system services ftp"
* will load 'ftp' under the 'systems services' hierarchy.
* @param loadType You can choose "merge" or "replace" as the loadType.
* NOTE: This parameter's value is redundant in case the file contains
* configuration in 'set' format.
* @throws java.io.IOException if there are errors communication with the netconf server.
* @throws org.xml.sax.SAXException if there are errors parsing the XML reply.
*/
public void commitThisConfiguration(String configFile, String loadType) throws IOException, SAXException {
requireCandidateCapability("commitThisConfiguration");
String configuration = readConfigFile(configFile);
configuration = configuration.trim();
if (!this.lockConfig()) {
throw new IOException("Unclean lock operation. Cannot proceed " +
"further.");
}
Throwable pendingFailure = null;
try {
if (configuration.startsWith("<")) {
this.loadXMLConfiguration(configuration, loadType);
} else if (configuration.startsWith("set")) {
this.loadSetConfiguration(configuration);
} else {
this.loadTextConfiguration(configuration, loadType);
}
this.commit();
} catch (Throwable t) {
pendingFailure = t;
throw t;
} finally {
try {
this.unlockConfig();
} catch (IOException e) {
if (pendingFailure != null) {
pendingFailure.addSuppressed(e);
} else {
throw e;
}
}
}
}
/**
* Commit the candidate configuration.
*
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
*/
public void commit() throws IOException, SAXException {
requireCandidateCapability("commit");
String rpc = "<rpc>" +
"<commit/>" +
"</rpc>" +
NetconfConstants.DEVICE_PROMPT;
setLastRpcReply(getRpcReply(rpc));
if (hasError() || !isOK()) {
throw new CommitException(
RpcErrorException.buildMessage("Commit operation", lastRpcReplyObject),
lastRpcReplyObject
);
}
}
/**
* Sends a *confirmed* <commit> request that follows the original
* RFC 6241 §8.4 semantics (confirmed‑commit **1.0**).
* <p>
* The server will roll back the candidate configuration unless a
* non‑confirmed <commit> is issued from **the same session**
* within the given timeout period.
* </p>
*
* @param seconds the <confirm-timeout> in seconds; if {@code seconds
* <= 0} the device’s default (600 s) is used
* @throws IOException if communication with the device fails
*
* @deprecated Prefer {@link #commitConfirm(long, String)} which adds
* the <code><persist></code> / <code><persist-id></code>
* parameters required by the
* <em>:confirmed-commit:1.1</em> capability.
*/
@Deprecated
public void commitConfirm(long seconds) throws IOException {
commitConfirm(seconds, null);
}
/**
* Issues a <em>confirmed</em> commit as defined by the
* <a href="https://datatracker.ietf.org/doc/html/rfc6241#section-8.4">
* :confirmed-commit:1.1 capability</a>.
*
* @param seconds confirm‑timeout (600 s default). If {@code seconds <= 0}