blib/lib/WWW/Splunk/API.pm untested

filter: Statementstmt 0.0% 0 / 96 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 14 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 167 CC 19 SCAR 52.7
CC
19
Cov
0%
request
342.0
new
6.0
delete
2.0
CRAP 193.5
1 =head1 NAME
2  
3 WWW::Splunk::API - Splunk REST client
4  
5 =head1 DESCRIPTION
6  
7 L<WWW::Splunk::API> is a low-level interface to Splunk
8 log search engine. It deals with HTTP communication as well as
9 working around certain interface glitches.
10  
11 See L<http://www.splunk.com/base/Documentation/latest/Developer/RESTSearch>
12 for API definition.
13  
14 This module is designed to be Splunk API version agnostic.
15  
16 =cut
17  
18 package WWW::Splunk::API;
19  
20 use LWP::UserAgent;
21 use HTTP::Request::Common;
22 use Text::CSV;
23 use WWW::Splunk::XMLParser;
24 use Carp;
25  
26 use strict;
27 use warnings;
28  
29 our $VERSION = '2.0';
30 our $prefix = '/services';
31  
32 =head2 B<new> (F<params>)
33  
34 A constructor.
35  
36 my $splunk = new WWW::Splunk::API ({
37 host => $host,
38 port => $port,
39 login => $login,
40 password => $password,
41 unsafe_ssl => 0,
42 });
43  
44 =cut
45 sub new
46 {
47 my $class = shift;
48 my $self = shift;
49  
50 $self->{port} ||= 8089;
51 $self->{host} ||= 'localhost';
52 $self->{url} ||= 'https://'.$self->{host}.':'.$self->{port};
53  
54 # Set up user agent unless an existing one was passed
55 unless ($self->{agent}) {
56 $self->{agent} = new LWP::UserAgent
57 (ssl_opts => {verify_hostname => (not $self->{unsafe_ssl})});
58 $self->{agent}->cookie_jar ({});
59 $self->{agent}->credentials (
60 delete ($self->{host}).':'.(delete $self->{port}),
61 '/splunk', delete $self->{login},
62 delete $self->{password});
63 $self->{agent}->agent ("$class/$VERSION ");
64 }
65  
66 bless $self, $class;
67 }
68  
69 =head2 B<delete> (F<parameters>)
70  
71 Wrapper around HTTP::Request::Common::DELETE ().
72  
73 =cut
74 sub delete
75 {
76 my $self = shift;
77 $self->request (\&DELETE, @_);
78 }
79  
80 =head2 B<post> (F<parameters>)
81  
82 Wrapper around HTTP::Request::Common::POST ().
83  
84 =cut
85 sub post
86 {
87 my $self = shift;
88 $self->request (\&POST, @_);
89 }
90  
91 =head2 B<get> (F<parameters>)
92  
93 Wrapper around HTTP::Request::Common::GET ().
94  
95 =cut
96 sub get
97 {
98 my $self = shift;
99 $self->request (\&GET, @_);
100 }
101  
102 =head2 B<head> (F<parameters>)
103  
104 Wrapper around HTTP::Request::Common::HEAD ().
105 Not used anywhere in splunk API
106  
107 =cut
108 sub head
109 {
110 my $self = shift;
111 $self->request (\&HEAD, @_);
112 }
113  
114 =head2 B<put> (F<parameters>)
115  
116 Wrapper around HTTP::Request::Common::PUT ().
117 Not used anywhere in splunk API
118  
119 =cut
120 sub put
121 {
122 my $self = shift;
123 $self->request (\&PUT, @_);
124 }
125  
126 =head2 B<request> (F<method>, F<location>, [F<data>], [F<callback>])
127  
128 Request a Splunk api and deal with the results.
129  
130 Method can be either a L<HTTP::Request> instance (see L<HTTP::Request::Common>
131 for useful ones), or a plain string, such as "GET" or "DELETE."
132  
133 Optional F<data> is has reference gets serialized into a request body for POST
134 request. Use I<undef> in case you don't have any data to send, but need to
135 specify a callback function in subsequent argument.
136  
137 Call-back function can be specified for a single special case, where a XML stream
138 of <results> elements is expected.
139  
140 =cut
141 sub request {
142 my $self = shift;
143 my $method = shift;
144 my $location = shift;
145 my $data = shift;
146 my $callback = shift;
147  
148 my $url = $self->{url}.$prefix.$location;
149  
150 # Construct the request
151 my $request;
152 if (ref $method and ref $method eq 'CODE') {
153 # Most likely a HTTP::Request::Common
154 $request = $method->($url, $data);
155 } else {
156 # A method string
157 $request = new HTTP::Request ($method, $url);
158 }
159  
160 my $content_type;
161 my $buffer;
162  
163 $self->{agent}->remove_handler ('response_header');
164 $self->{agent}->add_handler (response_header => sub {
165 my($response, $ua, $h) = @_;
166  
167 # Deal with HTTPS errors
168 # newer LWP::UserAgent does this right
169 if ($_ = $response->header ('Client-SSL-Warning')) {
170 # Why does LWP tolerate these by default?
171 croak "SSL Error: $_" unless $self->{unsafe_ssl};
172 }
173  
174 # Do not think of async processing of error responses
175 return 0 unless $response->is_success;
176  
177 # Decide if we're going async
178 $response->header ('Content-Type') =~ /^([^\s;]+)/
179 or croak "Missing or invalid Content-Type: $_";
180 $content_type = $1;
181  
182 if ($callback) {
183 $response->{default_add_content} = 0;
184 $buffer = "";
185 }
186 });
187  
188 $self->{agent}->remove_handler ('response_data');
189 $self->{agent}->add_handler (response_data => sub {
190 my ($response, $ua, $h, $data) = @_;
191  
192 return 1 unless defined $buffer;
193 $buffer .= $data;
194 foreach (split /<\/results>\K/, $buffer) {
195 unless (/<\/results>$/) {
196 $buffer = $_;
197 last;
198 }
199  
200 my $xml = XML::LibXML->load_xml (string => $_);
201 $callback->(WWW::Splunk::XMLParser::parse ($xml));
202 }
203  
204 return 1;
205 }) if $callback;
206  
207 # Run it
208 my $response = $self->{agent}->request ($request);
209 croak $response->header ('X-Died') if $response->header ('X-Died');
210  
211 # Deal with HTTP errors
212 unless ($response->is_success) {
213 my $content = WWW::Splunk::XMLParser::parse ($response->content)
214 if $response->header ('Content-Type') =~ /xml/;
215 my $error = "HTTP Error: ".$response->status_line;
216 $error .= sprintf "\n%s: %s",
217 $content->findvalue ('/response/messages/msg/@type'),
218 $content->findvalue ('/response/messages/msg')
219 if eval { $content->isa ('XML::LibXML::Document') }
220 and $content->documentElement->nodeName eq 'response';
221 croak $error;
222 }
223  
224 # We've gotten the response already
225 return if $callback;
226  
227 # Parse content from synchronous responses
228 # TODO: use callback and m_media_type matchspecs
229 if ($content_type eq 'text/xml') {
230 my $xml = XML::LibXML->load_xml (string => $response->content);
231 my @ret = WWW::Splunk::XMLParser::parse ($xml);
232 return $#ret ? @ret : $ret[0];
233 } elsif ($response->code eq 204) {
234 # "No content"
235 # Happens when events are requested immediately
236 # after the job is enqueued. With a text/plain content type
237 # Empty array is the least disturbing thing to return here
238 return ();
239 } elsif ($content_type eq 'text/plain') {
240 # Sometimes an empty text/plain body is sent
241 # even without 204 return code.
242 return ();
243 } else {
244 # TODO: We probably can't do much about RAW
245 # format, yet we could parse at least JSON
246 croak "Unknown content type: $content_type";
247 }
248 }
249  
250 =head1 SEE ALSO
251  
252 L<WWW::Splunk>, L<sc>
253  
254 =head1 AUTHORS
255  
256 Lubomir Rintel, L<< <lkundrak@v3.sk> >>
257  
258 The code is hosted on GitHub L<http://github.com/lkundrak/perl-WWW-Splunk>.
259 Bug fixes and feature enhancements are always welcome.
260  
261 =cut