blib/lib/HealthCheck/Diagnostic/WebRequest.pm

filter: Statementstmt 98.8% 88 / 89 Branchbran 83.3% 35 / 42 Conditioncond 60.4% 26 / 43 MC/DCmcdc 52.1% 12 / 23 Subroutinesub 100% 13 / 13 Podpod 60.0% 3 / 5 totaltotal 82.3% 177 / 215 CC 40 SCAR 30.4
CC
40
Cov
86%
new
39.5
check_status
12.0
check_content
4.0
CRAP 21.0
↑ Summary
1 package HealthCheck::Diagnostic::WebRequest;
2 2 ▶use parent 'HealthCheck::Diagnostic';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 # ABSTRACT: Make HTTP/HTTPS requests to web servers to check connectivity
5 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 our $VERSION = 'v1.4.2'; # VERSION
7  
8 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 sub new {
17 15 ▶ my ($class, @params) = @_;
Subroutine new: called CC=23 SCAR=36.8
Pod documented
18  
19 my %params = @params == 1 && ( ref $params[0] || '' ) eq 'HASH'
20 15 ▶ ? %{ $params[0] } : @params;
Branch: 1 branch
BranchTrueFalseTotal
@params == 1 && (ref $params[0] || '') eq 'HASH' ? : 0 15 15
Condition20%1/5
@params == 1 and (ref $params[0] || "") eq "HASH"
!ll&&!rl&&r
1500
ref $params[0] || ''
l!l
00
MC/DC0%0/2
@params == 1 and (ref $params[0] || "") eq "HASH"
@params == 1 ref $params[0]
Truth table33%1/3
A and B
A= @params == 1B= ref $params[0]
ABresult
0X0
100
111
21  
22 my @bad_params = grep {
23 15 !/^( content_regex
24 | id
25 | label
26 | no_follow_redirects
27 | options
28 | request
29 | status_code
30 | status_code_eval
31 | tags
32 | timeout
33 | url
34 )$/x
35 } keys %params;
36  
37 15 ▶ carp("Invalid parameter: " . join(", ", @bad_params)) if @bad_params;
Branch: 1 branch
BranchTrueFalseTotal
if @bad_params 0 15 15
38  
39 die "No url or HTTP::Request specified!" unless ($params{url} ||
40 ($params{request} && blessed $params{request} &&
41 15 ▶ $params{request}->isa('HTTP::Request')));
Branch: 1 branch
BranchTrueFalseTotal
unless $params{"url"} or $params{"request"} and builtin::blessed($params{"request"}) and $params{"request"}->isa("HTTP::Request") 0 15 15
Condition11%1/9
$params{"url"} or $params{"request"} and builtin::blessed($params{"request"}) and $params{"request"}->isa("HTTP::Request")
l!l&&r!l&&!r
1500
$params{"request"} and builtin::blessed($params{"request"}) and $params{"request"}->isa("HTTP::Request")
!ll&&!rl&&r
000
$params{"request"} and builtin::blessed($params{"request"})
!ll&&!rl&&r
000
MC/DC0%0/4
$params{"url"} or $params{"request"} and builtin::blessed($params{"request"}) and $params{"request"}->isa("HTTP::Request")
$params{"url"} $params{"request"} builtin::blessed($params{"request"}) $params{"request"}->isa("HTTP::Request")
Truth table20%1/5
A or B and C and D
A= $params{"url"}B= $params{"request"}C= builtin::blessed($params{"request"})D= $params{"request"}->isa("HTTP::Request")
ABCDresult
1XXX1
01111
00XX0
010X0
01100
42 die "The 'request' and 'url' options are mutually exclusive!"
43 15 ▶ if $params{url} && $params{request};
Branch: 1 branch
BranchTrueFalseTotal
if $params{"url"} and $params{"request"} 0 15 15
Condition33%1/3
$params{"url"} and $params{"request"}
!ll&&!rl&&r
0150
MC/DC0%0/2
$params{"url"} and $params{"request"}
$params{"url"} $params{"request"}
Truth table33%1/3
A and B
A= $params{"url"}B= $params{"request"}
ABresult
0X0
100
111
44  
45 # Process and serialize the status code checker
46 15 ▶ $params{status_code} ||= '200';
Condition100%2/2
$params{"status_code"} ||= 200
l!l
69
MC/DC100%1/1
$params{"status_code"} ||= 200
$params{"status_code"}
Truth table100%2/2
A
A= $params{"status_code"}
Aresult
11
00
47 15 my (@and, @or);
48 15 foreach my $part (split qr{\s*,\s*}, $params{status_code}) {
49 # Strict validation of each part, since we're throwing these into an eval
50 17 my ($op, $code) = $part =~ m{\A\s*(>=|>|<=|<|!=|!)?\s*(\d{3})\z};
51  
52 17 ▶ die "The 'status_code' condition '$part' is not in the correct format!"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 0 17 17
53 unless defined $code;
54 17 ▶ $op = '!=' if defined $op && $op eq '!';
Branch: 1 branch
BranchTrueFalseTotal
if defined $op and $op eq "!" 3 14 17
Condition100%3/3
defined $op and $op eq "!"
!ll&&!rl&&r
1043
MC/DC100%2/2
defined $op and $op eq "!"
defined $op $op eq "!"
Truth table100%3/3
A and B
A= defined $opB= $op eq "!"
ABresult
0X0
100
111
55  
56 17 ▶ unless ($op) { push @or, '$_ == '.$code; }
Branch: 1 branch
BranchTrueFalseTotal
if ($op) { } 7 10 17
57 7 else { push @and, '$_ '."$op $code"; }
58 }
59 15 ▶ push @or, '('.join(' && ', @and).')' if @and; # merge @and as one big condition into @or
Branch: 1 branch
BranchTrueFalseTotal
if @and 6 9 15
60 15 $params{status_code_eval} = join ' || ', @or;
61  
62 15 ▶ $params{request} //= HTTP::Request->new('GET', $params{url});
Condition33%1/3
$params{"request"} //= "HTTP::Request"->new("GET", $params{"url"})
l!l&&r!l&&!r
0150
MC/DC0%0/2
$params{"request"} //= "HTTP::Request"->new("GET", $params{"url"})
$params{"request"} "HTTP::Request"->new("GET", $params{"url"})
Truth table33%1/3
A //= B
A= $params{"request"}B= "HTTP::Request"->new("GET", $params{"url"})
ABresult
1X1
011
000
63 15 ▶ $params{options} //= {};
Condition100%2/2
$params{"options"} //= {}
l!l
213
MC/DC100%1/1
$params{"options"} //= {}
$params{"options"}
Truth table100%2/2
A
A= $params{"options"}
Aresult
11
00
64 15 ▶ $params{options}{agent} //= LWP::UserAgent->_agent .
Condition75%3/4
$params{"options"}{"agent"} //= "LWP::UserAgent"->_agent . ' HealthCheck-Diagnostic-WebRequest/' . ($class->VERSION || 0)
l!l
114
$class->VERSION || '0'
l!l
140
MC/DC100%1/1
$params{"options"}{"agent"} //= "LWP::UserAgent"->_agent . ' HealthCheck-Diagnostic-WebRequest/' . ($class->VERSION || 0)
$params{"options"}{"agent"}
MC/DC0%0/1
$class->VERSION || '0'
$class->VERSION
Truth table100%2/2
A
A= $params{"options"}{"agent"}
Aresult
11
00
Truth table50%1/2
A
A= $class->VERSION
Aresult
11
00
65 " HealthCheck-Diagnostic-WebRequest/" . ( $class->VERSION || '0' );
66 15 ▶ $params{options}{timeout} //= 7; # Decided by committee
Condition100%2/2
$params{"options"}{"timeout"} //= 7
l!l
114
MC/DC100%1/1
$params{"options"}{"timeout"} //= 7
$params{"options"}{"timeout"}
Truth table100%2/2
A
A= $params{"options"}{"timeout"}
Aresult
11
00
67  
68 15 return $class->SUPER::new(
69 label => 'web_request',
70 %params,
71 );
72 }
73  
74 sub check {
75 21 ▶ my ($self, @args) = @_;
Subroutine check: called CC=2 SCAR=6.9
Pod documented
76  
77 21 ▶ croak("check cannot be called as a class method")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 1 20 21
78 unless ref $self;
79 20 return $self->SUPER::check(@args);
80 }
81  
82 sub run {
83 20 ▶ my ( $self, %params ) = @_;
Subroutine run: called CC=3 SCAR=11.0
Pod documented
84 20 my $ua = LWP::UserAgent->new( %{$self->{options}} );
85  
86 20 ▶ $ua->requests_redirectable([]) if $self->{'no_follow_redirects'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"no_follow_redirects"} 0 20 20
87  
88 20 my $response = $ua->request( $self->{request} );
89  
90 20 my @results = $self->check_status( $response );
91 push @results, $self->check_content( $response )
92 20 ▶ if $results[0]->{status} eq 'OK';
Branch: 1 branch
BranchTrueFalseTotal
if $results[0]{"status"} eq "OK" 10 10 20
93  
94 20 my $info = join '; ', grep { length } map { $_->{info} } @results;
95  
96 20 return { info => $info, results => \@results };
97 }
98  
99 sub check_status {
100 20 ▶ my ( $self, $response ) = @_;
Subroutine check_status: called CC=12 SCAR=24.9
Pod undocumented
101 20 my $status;
102  
103 20 ▶ my $client_warning = $response->header('Client-Warning') // '';
Condition100%2/2
$response->header("Client-Warning") // ""
l!l
614
MC/DC100%1/1
$response->header("Client-Warning") // ""
$response->header("Client-Warning")
Truth table100%2/2
A
A= $response->header("Client-Warning")
Aresult
11
00
104 20 ▶ my $proxy_error = $response->header('X-Squid-Error') // '';
Condition100%2/2
$response->header("X-Squid-Error") // ""
l!l
119
MC/DC100%1/1
$response->header("X-Squid-Error") // ""
$response->header("X-Squid-Error")
Truth table100%2/2
A
A= $response->header("X-Squid-Error")
Aresult
11
00
105  
106 # Eval the status checker
107 20 my $success;
108 {
109 20 local $_ = $response->code;
110 20 $success = eval $self->{status_code_eval};
111 }
112  
113 # An unfortunate post-constructor die, but this would be a validation bug (ie: our fault)
114 20 ▶ die "Status code checker eval '".$self->{status_code_eval}."' failed: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 20 20
115  
116 20 ▶ $status = $success ? 'OK' : 'CRITICAL';
Branch: 1 branch
BranchTrueFalseTotal
$success ? : 11 9 20
117  
118 # Proxy error is an automatic failure
119 20 ▶ $status = 'CRITICAL' if $proxy_error;
Branch: 1 branch
BranchTrueFalseTotal
if $proxy_error 1 19 20
120  
121 my $info = sprintf( "Requested %s and got%s status code %s",
122 $self->{request}->uri,
123 20 ▶ $status eq 'OK' ? ' expected' : '',
Branch: 1 branch
BranchTrueFalseTotal
$status eq 'OK' ? : 10 10 20
124 $response->code,
125 );
126 20 ▶ $info .= " from proxy with error '$proxy_error'" if $proxy_error;
Branch: 1 branch
BranchTrueFalseTotal
if $proxy_error 1 19 20
127 20 ▶ $info .= ", expected ".$self->{status_code} unless $status eq 'OK' || $proxy_error;
Branch: 1 branch
BranchTrueFalseTotal
unless $status eq "OK" or $proxy_error 9 11 20
Condition100%3/3
$status eq "OK" or $proxy_error
l!l&&r!l&&!r
1019
MC/DC100%2/2
$status eq "OK" or $proxy_error
$status eq "OK" $proxy_error
Truth table100%3/3
A or B
A= $status eq "OK"B= $proxy_error
ABresult
1X1
011
000
128  
129 # If LWP returned 'Internal response', the status code doesn't actually mean anything
130 20 ▶ if ($client_warning && $client_warning eq 'Internal response') {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_warning and $client_warning eq "Internal response") 2 18 20
Condition100%3/3
$client_warning and $client_warning eq "Internal response"
!ll&&!rl&&r
1442
MC/DC100%2/2
$client_warning and $client_warning eq "Internal response"
$client_warning $client_warning eq "Internal response"
Truth table100%3/3
A and B
A= $client_warningB= $client_warning eq "Internal response"
ABresult
0X0
100
111
131 2 $status = 'CRITICAL';
132 2 $info = "User Agent returned: ".$response->message;
133 }
134  
135 20 return { status => $status, info => $info };
136 }
137  
138 sub check_content {
139 10 ▶ my ( $self, $response ) = @_;
Subroutine check_content: called CC=4 SCAR=13.9
Pod undocumented
140  
141 10 ▶ return unless $self->{content_regex};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"content_regex"} 6 4 10
142  
143 4 my $regex = $self->{content_regex};
144 4 my $content = $response->content;
145 4 ▶ my $status = $content =~ /$regex/ ? 'OK' : 'CRITICAL';
Branch: 1 branch
BranchTrueFalseTotal
$content =~ /$regex/ ? : 2 2 4
146 4 ▶ my $successful = $status eq 'OK' ? 'matches' : 'does not match';
Branch: 1 branch
BranchTrueFalseTotal
$status eq 'OK' ? : 2 2 4
147  
148 return {
149 4 status => $status,
150 info => "Response content $successful /$regex/",
151 };
152 }
153  
154 2 1;
155  
156 __END__
157  
158 =pod
159  
160 =encoding UTF-8
161  
162 =head1 NAME
163  
164 HealthCheck::Diagnostic::WebRequest - Make HTTP/HTTPS requests to web servers to check connectivity
165  
166 =head1 VERSION
167  
168 version v1.4.2
169  
170 =head1 SYNOPSIS
171  
172 # site: https://foo.com
173 # content: <html><head></head><body>This is my content</body></html>
174  
175 use HealthCheck::Diagnostic::WebRequest;
176  
177 # Look for a 200 status code and pass.
178 my $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
179 url => 'https://foo.com',
180 );
181 my $result = $diagnostic->check;
182 print $result->{status}; # OK
183  
184 # Look for a 401 status code and fail.
185 $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
186 url => 'https://foo.com',
187 status_code => 401,
188 );
189 $result = $diagnostic->check;
190 print $result->{status}; # CRITICAL
191  
192 # Look for any status code less than 500.
193 $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
194 url => 'https://foo.com',
195 status_code => '<500',
196 );
197 $result = $diagnostic->check;
198 print $result->{status}; # CRITICAL
199  
200 # Look for any 403, 405, or any 2xx range code
201 $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
202 url => 'https://foo.com',
203 status_code => '403, 405, >=200, <300',
204 );
205 $result = $diagnostic->check;
206 print $result->{status}; # CRITICAL
207  
208 # Look for a 200 status code and content matching the string regex.
209 $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
210 url => 'https://foo.com',
211 content_regex => 'is my',
212 );
213 $result = $diagnostic->check;
214 print $result->{status}; # OK
215  
216 # Use a regex as the content_regex.
217 $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
218 url => 'https://foo.com',
219 content_regex => qr/is my/,
220 );
221 $result = $diagnostic->check;
222 print $result->{status}; # OK
223  
224 # POST Method: Look for a 200 status code and content matching the string.
225 my $data = {
226 foo => 'tell me something',
227 };
228  
229 my $encoded_data = encode_utf8(encode_json($data));
230 my $header = [ 'Content-Type' => 'application/json; charset=UTF-8' ];
231 my $url = 'https://dev.payment-express.net/dev/env_test';
232  
233 my $request = HTTP::Request->new('POST', $url, $header, $encoded_data);
234 $diagnostic = HealthCheck::Diagnostic::WebRequest->new(
235 request => $request,
236 status_code => 200,
237 content_regex => "tell me something",
238 );
239  
240 $result = $diagnostic->check;
241 print $result->{status}; # OK
242  
243 =head1 DESCRIPTION
244  
245 Determines if a web request to a C<url> or C<request> is achievable.
246 Also has the ability to check if the HTTP response contains the
247 right content, specified by C<content_regex>. Sets the C<status> to "OK"
248 or "CRITICAL" based on the success of the checks.
249  
250 =head1 ATTRIBUTES
251  
252 =head2 url
253  
254 The site that is checked during the HealthCheck. It can be any HTTP/S link.
255 By default, it will send GET requests. Use L</request> if you want a more
256 complicated HTTP request.
257  
258 Either this option or L</request> are required, and are mutually exclusive.
259  
260 =head2 request
261  
262 Allows passing in L<HTTP::Request> object in order to use other HTTP request
263 methods and form data during the HealthCheck.
264  
265 Either this option or L</url> are required, and are mutually exclusive.
266  
267 =head2 status_code
268  
269 The expected HTTP response status code, or a string of status code conditions.
270  
271 Conditions are comma-delimited, and can optionally have an operator prefix. Any
272 condition without a prefix goes into an C<OR> set, while the prefixed ones go
273 into an C<AND> set. As such, C<==> is not allowed as a prefix, because it's less
274 confusing to not use a prefix here, and more than one condition while a C<==>
275 condition exists would not make sense.
276  
277 Some examples:
278  
279 !500 # Anything besides 500
280 200, 202 # 200 or 202
281 200, >=300, <400 # 200 or any 3xx code
282 <400, 405, !202 # Any code below 400 except 202, or 405,
283 # ie: (<400 && !202) || 405
284  
285 The default value for this is '200', which means that we expect a successful request.
286  
287 =head2 content_regex
288  
289 The content regex to test for in the HTTP response.
290 This is an optional field and is only checked if the status
291 code check passes.
292 This can either be a I<string> or a I<regex>.
293  
294 =head2 no_follow_redirects
295  
296 Setting this variable prevents the healthcheck from following redirects.
297  
298 =head2 options
299  
300 See L<LWP::UserAgent> for available options. Takes a hash reference of key/value
301 pairs in order to configure things like ssl_opts, timeout, etc.
302  
303 It is optional.
304  
305 By default provides a custom C<agent> string and a default C<timeout> of 7.
306  
307 =head1 DEPENDENCIES
308  
309 L<HealthCheck::Diagnostic>
310 L<LWP::UserAgent>
311  
312 =head1 CONFIGURATION AND ENVIRONMENT
313  
314 None
315  
316 =head1 AUTHOR
317  
318 Grant Street Group <developers@grantstreet.com>
319  
320 =head1 COPYRIGHT AND LICENSE
321  
322 This software is Copyright (c) 2018 - 2021 by Grant Street Group.
323  
324 This is free software, licensed under:
325  
326 The Artistic License 2.0 (GPL Compatible)
327  
328 =cut
↑ Summary