blib/lib/Monitoring/Icinga2/Client/REST.pm untested

filter: Statementstmt 0.0% 0 / 139 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 223 CC 19 SCAR 31.2
CC
19
Cov
0%
do_request
56.0
new
42.0
export
30.0
CRAP 22.8
1 package Monitoring::Icinga2::Client::REST;
2  
3 use strict;
4 use warnings;
5 use 5.010_001;
6 use Carp;
7 use LWP::UserAgent;
8 use HTTP::Request;
9 use URI::Escape;
10 use JSON;
11 use Encode qw( encode_utf8 );
12 use Scalar::Util 'looks_like_number';
13 use version 0.77; our $VERSION = version->declare('2.0.4');
14  
15 sub new {
16 my ($class, $hostname, $port, $path, $version, $insecure) = @_;
17 my $cafile;
18  
19 defined $hostname
20 or croak "hostname argument is required";
21  
22 unless( looks_like_number($port) ) {
23 # enable hash-style arg passing
24 my %args = @_[2..$#_];
25 $port = $args{port};
26 $path = $args{path};
27 $version = $args{version};
28 $insecure = $args{insecure};
29  
30 if(defined $args{cacert}) {
31 # Set ENV variable in case we're using Net::SSL for LWP's HTTPS
32 $cafile = $ENV{HTTPS_CA_FILE} = $args{cacert};
33 }
34 }
35  
36 my $self = bless {
37 hostname => $hostname,
38 port => $port // 5665,
39 path => $path // '/',
40 version => $version // 1,
41 }, $class;
42  
43 $self->{path} .= "/" unless $self->{path} =~ /\/$/;
44  
45 $self->{url} = sprintf(
46 "https://%s:%d%sv%d",
47 @$self{qw/ hostname port path version /}
48 );
49  
50 $self->{ua} = LWP::UserAgent->new(
51 $insecure ? (
52 ssl_opts => {
53 # Don't verify certs with either SSL module used by LWP
54 verify_hostname => 0,
55 SSL_verify_callback => sub { 1 },
56 # Set ca_file for IO::Socket::SSL
57 defined $cafile ? ( SSL_ca_file => $cafile) : (),
58 },
59 ) : (),
60 );
61  
62 $self->{ua}->default_header( 'Accept' => 'application/json' );
63 $self->{login_status} = "not logged in";
64  
65 return $self;
66 }
67  
68 sub do_request {
69 my ( $self, $method, $uri, $params, $data, $plaintext ) = @_;
70  
71 my $request_url = "$self->{url}/$uri";
72 $request_url .= '?' . _encode_params($params) if $params;
73  
74 my $req = HTTP::Request->new( $method => $request_url );
75  
76 if ($data) {
77 $data = encode_json($data);
78 $req->content($data);
79 }
80  
81 $self->{res} = $self->{ua}->request($req);
82  
83 return unless $self->{res}->is_success;
84  
85 # Try with first plaintext if plaintext is set
86 if ($plaintext) {
87 my $str = encode_utf8( $self->{res}->content );
88 if ($str) {
89 return $str;
90 }
91 }
92  
93 # Handle non utf8 chars
94 my $json_result = decode_json( encode_utf8( $self->{res}->content ) );
95 if ($json_result) {
96 return $json_result;
97 }
98 return;
99 }
100  
101 sub _encode_params {
102 return join '&', map { _encode_param($_) } split /&/, shift;
103 }
104  
105 sub _encode_param {
106 return join '=', map { uri_escape( $_ ) } split /=/, shift;
107 }
108  
109 {
110 my %type2keys = (
111 CheckCommand => [
112 [ qw/ arguments command env vars timeout / ],
113 [ qw/ templates zone / ],
114 ],
115 Downtime => [
116 [ qw/ author comment duration end_time entry_time fixed
117 host_name service_name start_time vars triggers /
118 ],
119 [ qw/ templates zone / ],
120 ],
121 Host => [
122 [ qw/ address6 address check_command display_name event_command
123 action_url notes notes_url vars icon_image icon_image_alt
124 check_interval max_check_attempts retry_interval /
125 ],
126 [ qw/ check_period check_timeout enable_active_checks
127 enable_event_handler enable_flapping enable_notifications
128 enable_passive_checks enable_perfdata groups notes
129 retry_interval templates zone /
130 ],
131 ],
132 HostGroup => [
133 [ qw/ action_url display_name notes notes_url vars / ],
134 [ qw/ groups templates zone / ],
135 ],
136 ScheduledDowntime => [
137 [ qw/ author comment duration fixed host_name ranges
138 service_name /
139 ],
140 [ qw/ templates zone / ],
141 ],
142 Service => [
143 [ qw/ vars action_url check_command check_interval display_name
144 notes notes_url event_command max_check_attempts
145 retry_interval /
146 ],
147 [ qw/ check_period check_timeout enable_active_checks
148 enable_event_handler enable_flapping enable_notifications
149 enable_passive_checks enable_perfdata groups icon_image
150 icon_image_alt notes templates zone /
151 ],
152 ],
153 ServiceGroup => [
154 [ qw/ action_url display_name notes notes_url vars / ],
155 [ qw/ groups templates zone / ],
156 ],
157 TimePeriod => [
158 [ qw/ display_name excludes includes prefer_includes
159 ranges vars /
160 ],
161 [ qw/ templates zone / ],
162 ],
163 User => [
164 [ qw/ display_name email enable_notifications pager states
165 period vars /
166 ],
167 [ qw/ groups templates zone / ],
168 ],
169 UserGroup => [
170 [ qw/ display_name vars / ],
171 [ qw/ groups templates zone / ],
172 ],
173 );
174  
175 sub export {
176 my ( $self, $full, $api_only ) = @_;
177 my $result = decode_json( encode_utf8( $self->{res}->content ) );
178 my $type = $result->{results}[0]{type};
179 # Do nothing if there is nothing to export
180 return unless $type;
181 # We only support certain object types
182 return unless exists $type2keys{$type};
183  
184 my @keys = @{$type2keys{$type}[0]};
185 push @keys, @{$type2keys{$type}[1]} if $full;
186  
187 my @results;
188 foreach my $object ( @{ $result->{results} } ) {
189 next if $api_only and $object->{attrs}{package} ne "_api";
190  
191 # The object needs to know its own name stored in a read/write field
192 $object->{attrs}{vars}{__export_name} = $object->{attrs}{__name};
193  
194 my %attrs;
195 @attrs{@keys} = @{$object->{attrs}}{@keys};
196 push @results, { attrs => \%attrs };
197 }
198 return \@results;
199 }
200 }
201  
202 sub login {
203 my ( $self, $username, $password ) = @_;
204  
205 return if $self->{logged_in};
206  
207 $self->{ua}->credentials( "$self->{hostname}:$self->{port}",
208 "Icinga 2", $username, $password );
209  
210 $self->do_request( "GET", "/status", "", "" );
211  
212 if ( $self->request_code == 200 ) {
213 $self->{login_status} = "login successful";
214 $self->{logged_in} = 1;
215 }
216 elsif ( $self->request_code == 401 ) {
217 $self->{login_status} = "wrong username/password";
218 }
219 else {
220 $self->{login_status} =
221 "unknown status line: " . $self->{res}->status_line;
222 }
223  
224 return $self->{logged_in};
225 }
226  
227 sub logout { shift->{logged_in} = undef; }
228 sub request_code { return shift->{res}->code; }
229 sub request_status_line { return shift->{res}->status_line; }
230 sub logged_in { return shift->{logged_in}; }
231 sub login_status { return shift->{login_status}; }
232  
233 1;