Netconf/Device.pm untested

filter: Statementstmt 0.0% 0 / 312 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 17 Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 494 CC 56 SCAR 41.0
CC
56
Cov
0%
generate_rpc
240.0
edit_config
72.0
send_and_recv_rpc
56.0
CRAP 60.1
1 # Net::Netconf::Device - Implements a remote Netconf device
2  
3 package Net::Netconf::Device;
4 use strict;
5 use Net::Netconf::Trace;
6 use Net::Netconf::Constants;
7 use Net::Netconf::Access;
8 use XML::LibXML;
9 use XML::LibXML::SAX;
10 use XML::LibXML::SAX::Parser;
11 use Net::Netconf::SAXHandler;
12 use File::Basename;
13 use Carp;
14 no strict 'subs';
15 require Exporter;
16  
17 use vars qw(@EXPORT);
18 use vars qw(@ISA);
19 use vars qw($AUTOLOAD);
20  
21 our $VERSION ='0.01';
22 my $NO_ARGS = bless {}, 'NO_ARGS';
23 my $TOGGLE = bless { 1 => 1 }, 'TOGGLE';
24 my $TOGGLE_NO = bless {}, 'TOGGLE';
25 my $STRING = bless {}, 'STRING';
26 my $DOM = bless {}, 'DOM';
27 my $ATTRIBUTE = bless {}, 'ATTRIBUTE';
28  
29 my $URL_STRING = bless {}, 'URL_STRING';
30 my $DOM_STRING = bless {}, 'DOM_STRING';
31 my $message_id = 1; # message-id for the rpc request
32  
33 # Capabilities supported
34 my $capability = 'http://xml.juniper.net/netconf/junos/1.0';
35  
36 my %methods = (
37 'get_xnm_information' => {
38 'type' => $STRING,
39 'namespace' => $STRING
40 },
41 'get' => {
42 filter => $DOM
43 },
44 'lock_config' => {
45 'tag_name' => 'lock',
46 'target' => $DOM_STRING,
47 'target_url' => $URL_STRING
48 },
49 'unlock_config' => {
50 'tag_name' => 'unlock',
51 'target' => $DOM_STRING,
52 'target_url' => $URL_STRING
53 },
54 'kill_session' => {
55 'session_id' => $STRING
56 },
57 'close_session' => $NO_ARGS,
58 'get_config' => {
59 'source' => $DOM_STRING,
60 'source_url' => $URL_STRING,
61 'filter' => $DOM
62 },
63 'edit_config' => {
64 'operation' => $ATTRIBUTE,
65 'target' => $DOM_STRING,
66 'default_operation' => $STRING,
67 'test-option' => $STRING,
68 'error-option' => $STRING,
69 'url' => $STRING,
70 'config' => $DOM,
71 'config-text' => $STRING
72 },
73 'copy_config' => {
74 'target' => $DOM_STRING,
75 'target_url' => $URL_STRING,
76 'source' => $DOM_STRING,
77 'source_url' => $URL_STRING,
78 },
79 'delete_config' => {
80 'target' => $DOM_STRING,
81 'target_url' => $URL_STRING,
82 },
83 'discard_changes' => $NO_ARGS,
84 'commit' => {
85 'confirmed' => $TOGGLE,
86 'confirm_timeout' => $STRING
87 },
88 'validate' => {
89 'source' => $DOM_STRING,
90 'source_url' => $URL_STRING,
91 },
92 'get_database_status_information' => $NO_ARGS,
93 );
94  
95 #client's capabilities
96 my %capabilities = (
97 'urn:ietf:params:xml:ns:netconf:base:1.0' =>
98 [ 'get', 'get_config', 'edit_config', 'copy_config', 'delete_config',
99 'lock_config', 'unlock_config', 'close_session', 'kill_session',
100 'discard_changes'],
101 'urn:ietf:params:xml:ns:netconf:capability:candidate:1.0' => [ 'commit' ],
102 'urn:ietf:params:xml:ns:netconf:capability:confirmed-commit:1.0' => [],
103 'urn:ietf:params:xml:ns:netconf:capability:validate:1.0' => [ 'validate' ],
104 'urn:ietf:params:xml:ns:netconf:capability:url:1.0?protocol=http,ftp,file' => [],
105 );
106  
107 # get the message id
108 sub get_msg_id {
109 return $message_id++;
110 }
111  
112 # Create a new Netconf device object
113 # Connect to the Netconf server
114 sub new
115 {
116 my ($class, %args) = @_;
117 my $self = { %args };
118  
119 # Make sure we have 'login', 'hostname' and 'password'
120 croak 'missing information <hostname>' unless exists $args{'hostname'};
121 croak 'missing information <login>' unless exists $args{'login'};
122 croak 'missing information <password>' unless exists $args{'password'};
123  
124 # SAX Parser
125 my $handler = new Net::Netconf::SAXHandler('ErrorContext' => 5);
126 my $saxparser = new XML::LibXML::SAX::Parser('Handler' => $handler)
127 || croak 'Cannot create parser: ' . $!;
128 $self->{'sax_parser'} = $saxparser;
129  
130 # DOM parser
131 my $domparser = XML::LibXML->new();
132 $self->{'dom_parser'}= $domparser;
133  
134 # Bless ourselves
135 $class = ref($class) || $class;
136 bless $self, $class;
137  
138 # Connection state
139 $self->{'conn_state'} = Net::Netconf::Constants::NC_STATE_DISCONN;
140
141 # Default trace level: WARNING_LEVEL
142 $self->{'debug_level'} = Net::Netconf::Trace::WARNING_LEVEL unless
143 $self->{'debug_level'};
144  
145 # Create the trace object
146 $self->{'trace_obj'} = new Net::Netconf::Trace($self->{'debug_level'});
147  
148 # Now bring up the connection
149 return $self->connect() unless $self->{'do_not_connect'};
150 $self;
151 }
152  
153 # Open a connection to the Netconf server
154 sub connect
155 {
156 my($self) = @_;
157 my $conn;
158 my $trace_obj = $self->{'trace_obj'};
159 $trace_obj->trace(Net::Netconf::Trace::TRACE_LEVEL, 'preparing to connect');
160  
161 # If we are already connected, we have the connection object
162 # in $self->{conn_obj}
163 return $self if $self->{'conn_obj'};
164  
165 eval {
166 $conn = new Net::Netconf::Access($self); # $self = ssh , connect to ssh
167 };
168  
169 if ($@ || !ref($conn)) {
170 croak 'unable to create Access object' . $@;
171 }
172  
173 eval 'use ' . ref($conn);
174 if ($@) {
175 croak 'unable to create Access object using ' . $self->{'access'} . $@;
176 }
177  
178 $self->{'conn_obj'} = $conn;
179 unless (defined ($conn->connect())) {
180 croak 'unable to connect to the Netconf server';
181 }
182  
183 $self->send_and_recv_hello();
184 $self;
185 }
186  
187 # - If the user specifies client capabilities, it uses that to generate
188 # the client hello. Else, it uses the default capability list given
189 # by Net::Netconf::Constants::NC_DEFAULT_CAP.
190 # - Does the hello exchange
191 # - Parses the server hello to get the server capabilities
192 # - Initializes the Netconf API based on the server capabilities
193 sub send_and_recv_hello
194 {
195 my($self) = shift;
196 my $msg;
197 my $conn = $self->{'conn_obj'};
198 my $traceobj = $self->{'trace_obj'};
199 my @server_capabilities;
200  
201 # Generate the client capability using the capabilities passed to it
202 my $client_capability = <<EOF;
203 <hello>
204 <capabilities>
205 EOF
206  
207 my $cap = $self->{'client_capabilities'};
208 if ($cap) { # Client has specified some capability use that
209 foreach my $capelmt (@$cap) {
210 $client_capability .= <<EOF;
211 <capability>$capelmt</capability>
212 EOF
213 }
214 } else { # Use the default capability
215 my $default_capability = Net::Netconf::Constants::NC_DEFAULT_CAP;
216 $client_capability .= " $default_capability\n";
217 }
218 $client_capability .= <<EOF;
219 </capabilities>
220 </hello>
221 EOF
222  
223 # Send our capabilities to the Netconf server
224 # Get the server capability
225 my $server_cap = $self->send_and_recv_rpc($client_capability,
226 Net::Netconf::Constants::NC_HELLO_TAG,
227 Net::Netconf::Constants::NC_STATE_HELLO_SENT,
228 Net::Netconf::Constants::NC_STATE_HELLO_RECVD);
229  
230 $self->{'conn_state'} = Net::Netconf::Constants::NC_STATE_CONN;
231  
232 # Tracing what is going on
233 $traceobj->trace(Net::Netconf::Trace::DEBUG_LEVEL, <<EOF);
234 Client capability sent:
235 $client_capability
236 Server capability received:
237 $server_cap
238 EOF
239  
240 # Parse the server hello to extract the capabilities
241
242 eval {
243 $self->{'sax_parser'}->parse_string($server_cap);
244 };
245  
246 if ($@) {
247 $self->report_error(1, 'error in parsing server capability');
248 }
249  
250 # Now save the session-id and server capabilities
251 $self->{'session_id'} = $Net::Netconf::SAXHandler::session_id;
252 @{$self->{'server_capabilities'}} = @Net::Netconf::SAXHandler::parsed_cap;
253  
254 # See if any errors were emitted and save them
255 $self->{'found_rpc_errors'} = $Net::Netconf::SAXHandler::found_error;
256 if ($self->{'found_rpc_errors'}) {
257 %{$self->{'rpc_errors'}} = (%Net::Netconf::SAXHandler::rpc_errors);
258 }
259 $self;
260 }
261  
262 # This returns the server capability for Netconf session
263 sub get_server_cap
264 {
265 my ($self) = @_;
266 return @{$self->{'server_capabilities'}};
267 }
268  
269 # Disconnect from the Netconf server
270 # Free up resources
271 sub disconnect
272 {
273 my($self) = @_;
274 my $conn = $self->{'conn_obj'};
275 $conn->disconnect if ($conn and $self->{'conn_state'} !=
276 Net::Netconf::Constants::NC_STATE_DISCONN && not $conn->eof);
277 }
278  
279 # Helper function for sending and receiving Netconf commands and responses
280 # $xml = the xml string to send
281 # $endtag = we should read data till we find this tag (optional)
282 # $state_sent = state after we sent the data (optional)
283 # $state_recv = state after we receive data (optional)
284 sub send_and_recv_rpc
285 {
286 my($self, $xml, $endtag, $state_sent, $state_recv) = @_;
287 return unless ($xml);
288 my $conn = $self->{'conn_obj'};
289 my $traceobj = $self->{'trace_obj'};
290 my $in = '';
291 my $msg;
292 return unless ($xml);
293  
294 # Set the default values
295 $state_sent = Net::Netconf::Constants::NC_STATE_REQ_SENT unless ($state_sent);
296 $state_recv = Net::Netconf::Constants::NC_STATE_REQ_RECVD unless ($state_recv);
297 $endtag = Net::Netconf::Constants::NC_REPLY_TAG unless ($endtag);
298  
299 # Send the request to the Netconf server
300 unless ($conn->send($xml)) {
301 carp 'failed to send user request';
302 return;
303 };
304
305 $self->{'conn_state'} = $state_sent;
306
307 # Get a response from the Netconf server
308 $in = $self->read_rpc( $endtag );
309 $self->parse_response( $in );
310 }
311  
312 # Helper function to read RPC response until end tag
313 sub read_rpc
314 {
315 my $self = shift;
316 my $endtag = shift;
317
318 my $conn = $self->{'conn_obj'};
319 my $in = '';
320
321 while ( $self->{'conn_state'} != Net::Netconf::Constants::NC_STATE_HELLO_RECVD )
322 {
323 if ($conn->eof) {
324 $self->report_error(1, 'connection to Netconf server lost');
325 return undef;
326 }
327
328 $in .= $conn->recv();
329 # Check to see if you received the end-tag
330 if ($in =~ /<\/\s*$endtag\s*>/gs)
331 {
332 $self->{'conn_state'} = Net::Netconf::Constants::NC_STATE_HELLO_RECVD;
333 }
334 elsif ($conn->eof)
335 {
336 $self->report_error(1, 'connection to Netconf server lost');
337 return undef;
338 }
339 }
340
341 return $in;
342 }
343  
344 # Once we receive the response from the server, we call this method before passing
345 # the response to the parser. We strip the response off the namespace values.
346 sub parse_response
347 {
348 my ($self, $response) = @_;
349 return unless $response;
350 $self->{'found_rpc_errors'} = 0;
351 $self->{'rpc_errors'} = undef;
352 # For junos:style, junos:format stuff which gives error while parsing
353 $response =~ s/junos://g;
354 $self->{'server_response'} = $response;
355 eval {
356 $self->{'sax_parser'}->parse_string($response);
357 };
358 if ($@) { #parse error
359 carp 'error in parsing server response ' . "\n" . $response . "\n" . $@;
360 return $self->{'server_response'};
361 }
362  
363 # Save the total number of <rpc-error>s received and error information
364  
365 $self->{'found_rpc_errors'} = $Net::Netconf::SAXHandler::found_error;
366 # found_error an attribute of SAXHandler
367  
368 $self->{'no_error'} = $Net::Netconf::SAXHandler::no_error;
369 #no_error an attribute of SAXHandler
370  
371 # We should not get both <rpc-error> and <ok/>
372 #if ($self->{'found_rpc_errors'} && $self->{'no_error'}) {
373 # carp 'error in server response: has both <rpc-error> and <ok/> ' .
374 #"\n" . $response . "\n" . $@;
375 #return $self->{'server_response'};
376 #}
377  
378 if ($self->{'found_rpc_errors'}) {
379 %{$self->{'rpc_errors'}} = (%Net::Netconf::SAXHandler::rpc_errors);
380 }
381 # Then we return the response as a string
382 return $self->{'server_response'};
383 }
384  
385 # This creates a DOM tree from the server response and returns it
386 # This is useful for <get> and <get-config> operations
387 sub get_dom
388 {
389 print "inside dom object";
390 my($self) = @_;
391 # Create a DOM object and return that.
392 # Server response is in: $self->{server_response}
393 my $doc = $self->{'dom_parser'}->parse_string($self->{'server_response'});
394 $self->{'doc'} = $doc;
395 return $self->{'doc'};
396 }
397  
398 # This returns the session ID for this Netconf session
399 sub get_session_id
400 {
401 my ($self) = @_;
402 return $self->{'session_id'};
403 }
404  
405 # This returns the number of errors returned by the server
406 sub has_error
407 {
408 my ($self) = shift;
409 return $self->{'found_rpc_errors'};
410 }
411  
412 # This returns the first <rpc-error> emitted by the server as a hash reference.
413 # This also prints the errors in debug mode
414 sub get_first_error
415 {
416 my($self) = shift;
417 return unless ($self->{'found_rpc_errors'});
418 $self->print_error_info(1);
419 return $self->{'rpc_errors'}{1};
420 }
421  
422 # This returns all the errors emitted by the server as a hash reference
423 # This also prints the errors in debug mode
424 sub get_all_errors
425 {
426 my($self) = @_;
427 return unless ($self->{'found_rpc_errors'});
428 my $indx = 1;
429 while ($indx <= $self->{'found_rpc_errors'}) {
430 $self->print_error_info($indx);
431 $indx++;
432 }
433 return $self->{'rpc_errors'};
434 }
435  
436 # This prints the server error messages if in DEBUG_LEVEL
437 sub print_error_info
438 {
439 my $self = shift;
440 confess 'Usage: ' . __PACKAGE__ . '::print_error_info <key>' unless @_ == 1;
441 my $key = @_;
442 my $trace_obj = $self->{'trace_obj'};
443 my @error_tag = (
444 'error_type',
445 'error_tag',
446 'error_severity',
447 'error_path',
448 'error_message',
449 'error_info');
450 $trace_obj->trace(Net::Netconf::Trace::DEBUG_LEVEL,
451 'Server response HAD ERRORS ....');
452 foreach my $tag (@error_tag) {
453 if ($self->{'rpc_errors'}{$key}{$tag}) {
454 $trace_obj->trace(Net::Netconf::Trace::DEBUG_LEVEL,
455 $tag . '=' . $self->{'rpc_errors'}{$key}{$tag});
456 }
457 }
458 }
459  
460 # This prints the error message and quits the program based on $level
461 # $level > 0 means this is a fatal error, so quit
462 sub report_error
463 {
464 my $self = shift;
465 confess 'Usage: ' . __PACKAGE__ . '::report_error <level> <message>'
466 unless @_ == 2;
467 my ($level, $msg) = @_;
468 if ($level) {
469 $self->{'conn_obj'} = undef;
470 $self->{'trace_obj'} = undef;
471 # $self->{'sax_parser'} = undef;
472 croak $msg;
473 }
474 carp $msg;
475 }
476  
477 #This function generate rpc and call send_and recv_rpc() method
478 sub generate_rpc
479 {
480 my ($self,$fn, %args) = @_;
481 my $bindings = $methods{ $fn };
482 my $output = "";
483 my $tag = "";
484 my $attrs = "";
485 my $url = "";
486 my $msg_id = &get_msg_id;
487  
488 foreach my $field (keys(%args)) {
489 my $type = $bindings->{ $field };
490 my $value = $args{ $field };
491  
492 ($tag = $field) =~ s/_/-/g;
493  
494 if (ref($type) eq 'TOGGLE' || ref($value) eq 'TOGGLE') {
495 if ($value ne '0') {
496 $output .= " <$tag/>\n";
497 }
498  
499 } elsif (ref($value) eq 'TOGGLE_NO') {
500 if ($value eq '0') {
501 $output .= " <no-$tag/>\n";
502 } else {
503 $output .= " <$tag/>\n";
504 }
505  
506 } elsif (ref($type) eq 'STRING') {
507 $output .= " <${tag}>${value}</${tag}>\n";
508  
509 } elsif (ref($type) eq 'URL_STRING') {
510 ($tag, $url) = split(/[-_]/, $field);
511 $output .= " <${tag}><${url}>${value}</${url}></${tag}>\n";
512 }elsif (ref($type) eq 'DOM_STRING') {
513 if ($value =~ '<\/') {
514 $output .= " <${tag}>${value}</${tag}>\n";
515 } else {
516 $output .= " <${tag}><${value}/></${tag}>\n";
517 }
518 }elsif ($type =~ /(\d)+\.\.(\d)+/) {
519 $output .= " <${tag}>${value}</${tag}>\n";
520  
521 } elsif (ref($type) eq 'DOM') {
522 $output .= $value->toString;
523 $output .= "\n";
524  
525 } elsif (ref($type) eq 'ATTRIBUTE') {
526 $attrs .= " ${tag}=\"${value}\"\n";
527  
528 } elsif (ref($value)) {
529 $output .= $value->toString;
530 $output .= "\n";
531  
532 } else {
533 $output .= " <${tag}>${value}</${tag}>\n";
534 }
535 }
536 if ($bindings->{'tag_name'}) {
537 $fn = $bindings->{'tag_name'};
538 }
539
540 ($tag = $fn) =~ s/_/-/g;
541  
542 if ($output) {
543 $output = "<rpc message-id=\'$msg_id\'>\n <${tag}${attrs}>\n${output} </${tag}>\n</rpc>\n";
544 }
545 else {
546 $output = "<rpc message-id=\'$msg_id\'>\n <${tag}${attrs}/>\n</rpc>\n";
547 }
548 $self->{'request'} = $output;
549 $self->send_and_recv_rpc($output);
550 }
551  
552 # This will be removed after the <get-config> accepts parameters in any order
553 sub get_config
554 {
555 my ($self,%args) = @_;
556 my $msg_id = &get_msg_id;
557 my $request = '<rpc message-id=\'' . $msg_id . '\'>';
558 $request .= '<get-config> <source>';
559 if (exists $args{'source_url'}) {
560 $request .= '<url> <';
561 $request .= $args{'source_url'};
562 $request .= '/> </url> </source>';
563 } elsif (exists $args{'source'}) {
564 $request .= '<';
565 $request .= $args{'source'};
566 $request .= '/> </source>';
567 }
568 $request .= $args{filter};
569 $request .= '</get-config> </rpc>';
570 $self->send_and_recv_rpc($request);
571 }
572  
573 # This will be removed after the <edit-config> accepts parameters in any order
574 sub edit_config
575 {
576 my ($self,%args) = @_;
577 my $msg_id = &get_msg_id;
578 my $request = '<rpc message-id=\'' . $msg_id;
579 if (exists $args{'operation'}) {
580 $request = 'operation=\'' . $args{'operation'};
581 }
582 $request .= '\'>';
583 $request .= '<edit-config> <target>';
584 if (exists $args{'target'}) {
585 $request .= '<';
586 $request .= $args{'target'};
587 $request .= '/> </target>';
588 }
589  
590 if (exists $args{'default_operation'}) {
591 $request .= '<default-operation>';
592 $request .= $args{'default_operation'};
593 $request .= '</default-operation>';
594 }
595  
596 if (exists $args{'test_option'}) {
597 $request .= '<test-option>';
598 $request .= $args{'test_option'};
599 $request .= '</test-option>';
600 }
601
602 if (exists $args{'error_option'}) {
603 $request .= '<error-option>';
604 $request .= $args{'error_option'};
605 $request .= '</error-option>';
606 }
607  
608 if (exists $args{'url'}) {
609 $request .= '<url>' . $args{'url'} . '</url>';
610 } elsif (exists $args{'config-text'}) {
611 $request .= '<config-text>' . $args{'config-text'} . '</config-text>';
612 } else {
613 $request .= '<config>' . $args{'config'} . '</config>';
614 }
615 $request .= '</edit-config> </rpc>';
616 $self->send_and_recv_rpc($request);
617 }
618  
619 sub AUTOLOAD
620 {
621 my ($self, @args) = @_;
622 my $fn = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
623 return if $AUTOLOAD =~ /::DESTROY$/;
624 $self->generate_rpc($fn, @args);
625 }
626  
627 1;
628  
629 __END__