Jmx4Perl/Agent/Jolokia/Meta.pm untested

filter: Statementstmt 0.0% 0 / 159 Branchbran 0.0% 0 / 58 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 285 CC 30 SCAR 29.5
CC
30
Cov
0%
load
56.0
template_url
42.0
_check_version
30.0
CRAP 19.1
1 #!/usr/bin/perl
2  
3 package JMX::Jmx4Perl::Agent::Jolokia::Meta;
4  
5 use JMX::Jmx4Perl::Agent::Jolokia::DownloadAgent;
6 use JMX::Jmx4Perl::Agent::Jolokia::Logger;
7 use JMX::Jmx4Perl::Agent::Jolokia::Verifier;
8 use JSON;
9 use Data::Dumper;
10 use base qw(LWP::UserAgent);
11 use strict;
12  
13 my $JOLOKIA_META_URL = "http://www.jolokia.org/jolokia.meta";
14  
15 =head1 NAME
16  
17 JMX::Jmx4Perl::Agent::Jolokia::Meta - Fetches, caches and parses Meta data from
18 www.jolokia.org
19  
20 =head1 DESCRIPTION
21  
22 This class is responsible for fetching meta data about available agents from
23 Jolokia. It knows how to parse those meta data and caches it for subsequent
24 usage in the local file system.
25  
26 =head1 METHODS
27  
28 =over 4
29  
30 =item $meta = JMX::Jmx4Perl::Agent::Jolokia::Meta->new(....)
31  
32 Create a new meta object which handles downloading of Jolokia meta information
33 and caching this data.
34  
35 =cut
36  
37 sub new {
38 my $class = shift;
39 my $self = ref($_[0]) eq "HASH" ? $_[0] : { @_ };
40 # Dummy logging if none is provided
41 $self->{logger} = new JMX::Jmx4Perl::Agent::Jolokia::Logger::None unless $self->{logger};
42 $self->{verifier} = new JMX::Jmx4Perl::Agent::Jolokia::Verifier(logger => $self->{logger},ua_config => $self->{ua_config});
43 return bless $self,(ref($class) || $class);
44 }
45  
46 =item $meta->load($force)
47  
48 Load the meta data from the server or retrieve it from the cache. The data is
49 taken from the cache, if it is no older than $self->{cache_interval} seconds.
50 If $force is given and true, the data is always fetched fresh from the server.
51  
52 This method return $self so that it can be used for chaining. Any error or
53 progress infos are given through to the C<log_handler> provided during
54 construction time. This method will return C<undef> if the data can't be
55 loaded.
56  
57 =cut
58  
59 sub load {
60 my ($self,$force) = @_;
61 $force = $self->{force_load} unless defined($force);
62 my $meta_json;
63 my $cached = undef;
64 if (!$force) {
65 $meta_json = $self->_from_cache;
66 $cached = 1 if $meta_json;
67 }
68 $meta_json = $self->_load_from_server unless $meta_json; # Throws an error
69 # if it can't be
70 # loaded
71 return undef unless $meta_json;
72 $self->_to_cache($meta_json) unless $cached;
73 $self->{_meta} = $meta_json;
74 return $self;
75 }
76  
77 =item $meta->initialized()
78  
79 Returns C<true> if the meta data has been initialized, either by loading it or
80 by using a cached data. If false the data can be loaded via L<load>
81  
82 =cut
83  
84 sub initialized {
85 my $self = shift;
86 return defined($self->{_meta});
87 }
88  
89 =item $value = $meta->get($key)
90  
91 Get a value from the meta data.
92  
93 =cut
94  
95 sub get {
96 my $self = shift;
97 my $key = shift;
98 $self->_fatal("No yet loaded") unless $self->{_meta};
99 return $self->{_meta}->{$key};
100 }
101  
102  
103 =item $jolokia_version = $meta->latest_matching_version($jmx4perl_version)
104  
105 Get the latest matching Jolokia version for a given Jmx4Perl version
106  
107 =cut
108  
109 sub latest_matching_version {
110 my $self = shift;
111 my $jmx4perl_version = shift;
112 # Iterate over all existing versions, starting from the newest one,
113 # and return the first matching
114 my $version_info = $self->get("versions");
115 for my $v (sort { $self->compare_versions($b,$a) } grep { $_ !~ /-SNAPSHOT$/ } keys %$version_info) {
116 my $range = $version_info->{$v}->{jmx4perl};
117 if ($range) {
118 my $match = $self->_check_version($jmx4perl_version,$range);
119 #print "Match: $match for $range (j4p: $jmx4perl_version)\n";
120 return $v if $match;
121 }
122 }
123 return undef;
124 }
125  
126 # Compare two version which can contain one, two or more digits. Returns <0,0 or
127 # >0 if the first version is smaller, equal or larger than the second version.
128 # It doesn't take into account snapshot
129 sub compare_versions {
130 my $self = shift;
131 my @first = _split_version(shift);
132 my @second = _split_version(shift);
133 my $len = $#first < $#second ? $#first : $#second;
134 for my $i (0 ... $len) {
135 next if $first[$i] == $second[$i];
136 return $first[$i] - $second[$i];
137 }
138 return $#first - $#second;
139 }
140  
141 sub _split_version {
142 my $v = shift;
143 $v =~ s/-.*$//;
144 return split /\./,$v;
145 }
146  
147 sub _check_version {
148 my $self = shift;
149 my $jmx4perl_version = shift;
150 my $range = shift;
151
152 my ($l,$l_v,$u_v,$u) = ($1,$2,$3,$4) if $range =~ /^\s*([\[\(])\s*([\d\.]+)\s*,\s*([\d\.]+)\s*([\)\]])\s*$/;
153 if ($l_v) {
154 my $cond = "\$a " . ($l eq "[" ? ">=" : ">"). $l_v . " && \$a" . ($u eq "]" ? "<=" : "<") . $u_v;
155 my $a = $jmx4perl_version;
156 return eval $cond;
157 }
158 return undef;
159 }
160  
161 =item $meta->versions_compatible($jmx4perl_version,$jolokia_version)
162  
163 Check, whether the Jolokia and Jmx4Perl versions are compaptible, i.e.
164 whether Jmx4Perl with the given version can interoperate with the given
165 Jolokia version
166  
167 =cut
168  
169 sub versions_compatible {
170 my $self = shift;
171 my $jmx4perl_version = shift;
172 my $jolokia_version = shift;
173  
174 my $version_info = $self->get("versions");
175 my $range = $version_info->{$jolokia_version}->{jmx4perl};
176 if ($range) {
177 return $self->_check_version($jmx4perl_version,$range);
178 } else {
179 return undef;
180 }
181 }
182  
183 =item $type = $meta->extract_type($artifact_name)
184  
185 Extract the type for a given artifactId
186  
187 =cut
188  
189 sub extract_type {
190 my $self = shift;
191 my $artifact = shift;
192 my $mapping = $self->get("mapping");
193 for my $k (keys %$mapping) {
194 return $k if $mapping->{$k}->[0] eq $artifact;
195 }
196 return undef;
197 }
198  
199 =item $meta->template_url($template_name,$version)
200  
201 Download a template with the given name. The download URL is looked up
202 in the meta data. If a version is given, the template for this specific
203 version is returned (if present, if not the default template is returned).
204 If no version is given, the default template is returned. The downloaded
205 template is verified as any other downloaded artifact.
206  
207 The template is returned as a string.
208  
209 =cut
210  
211 sub template_url {
212 my $self = shift;
213 my $template = shift;
214 my $version = shift;
215
216 my $url;
217 if ($version) {
218 my $version_info = $self->get("versions");
219 my $v_data = $version_info->{$version};
220 $self->_fatal("Cannot load template $template for version $version since $version is unknown")
221 unless $v_data;
222 my $templs = $v_data->{templates};
223 if ($templs) {
224 $url = $templs->{$template};
225 }
226 }
227 unless ($url) {
228 my $templs = $self->get("templates");
229 $self->_fatal("No templates defined in jolokia.meta") unless $templs;
230 $url = $templs->{$template};
231 }
232 return $url;
233 }
234  
235  
236 =back
237  
238 =cut
239  
240 # ===================================================================================
241  
242 # Fetch from cache, but only if the cache file is older than $cache_interval
243 # seconds back in time
244 sub _from_cache {
245 my $self = shift;
246 my $cache_interval = $self->{cache_interval} || 12 * 60 * 60; # 12h by default
247 my $cache_file = $self->{cache_file} || $ENV{HOME} . "/.jolokia_meta";
248 my $mtime = (stat($cache_file))[9];
249 if ($mtime && $mtime >= time - $cache_interval) {
250 if (!open(F,$cache_file)) {
251 $self->_error("Cannot open $cache_file: $!");
252 return undef;
253 }
254 my $ret = join "",<F>;
255 close F;
256 $self->_debug("Loaded Jolokia meta data from cache");
257 return from_json($ret,{utf8 => 1});
258 } else {
259 return undef;
260 }
261 }
262  
263 # Store to cache
264 sub _to_cache {
265 my $self = shift;
266 my $meta = shift;
267 my $cache_file = $self->{cache_file} || $ENV{HOME} . "/.jolokia_meta";
268 if (!open(F,">$cache_file")) {
269 $self->_error("Cannot save $cache_file: $!");
270 return;
271 }
272 print F to_json($meta,{utf8 => 1,pretty => 1});
273 close F;
274 }
275  
276 # Load from server
277 sub _load_from_server {
278 my $self = shift;
279
280 # Create sample meta-data
281 return $self->_example_meta if ($ENV{USE_SAMPLE_JOLOKIA_META});
282  
283 # Load with HTTP-Client, hardcoded for now
284 $self->_info("Loading Jolokia meta data from $JOLOKIA_META_URL");
285  
286 my $ua = new JMX::Jmx4Perl::Agent::Jolokia::DownloadAgent($self->{ua_config});
287 my $response = $ua->get($JOLOKIA_META_URL);
288 if ($response->is_success) {
289 my $content = $response->decoded_content; # or whatever
290 $self->{verifier}->verify(ua_config => $self->{ua_config}, logger => $self->{logger},
291 url => $JOLOKIA_META_URL, data => $content);
292 return from_json($content, {utf8 => 1});
293 }
294 else {
295 # Log an error, but do not exit ...
296 $self->{logger}->error("Cannot load Jolokia Meta-Data from $JOLOKIA_META_URL: " . $response->status_line);
297 return undef;
298 }
299 }
300  
301 # Do something with errors and info messages
302  
303 sub _debug {
304 shift->{logger}->debug(@_);
305 }
306  
307 sub _error {
308 my $self = shift;
309 $self->{logger}->error(@_);
310 }
311  
312 sub _fatal {
313 my $self = shift;
314 $self->{logger}->error(@_);
315 die "\n";
316 }
317  
318 sub _info {
319 my $self = shift;
320 $self->{logger}->info(@_);
321 }
322  
323 # Sample meta data, also used for creating site meta data.
324 sub _example_meta {
325 return {
326 repositories => [
327 "http://labs.consol.de/maven/repository"
328 ],
329 'snapshots-repositories' => [
330 "http://labs.consol.de/maven/snapshots-repository"
331 ],
332 versions => {
333 "0.90-SNAPSHOT" => { jmx4perl => "[0.90,1.0)" },
334 "0.83" => { jmx4perl => "[0.73,1.0)" },
335 "0.82" => { jmx4perl => "[0.73,1.0)" } ,
336 "0.81" => { jmx4perl => "[0.73,1.0)" } ,
337 },
338 mapping => {
339 "war" => [ "jolokia-war", "jolokia-war-%v.war", "jolokia.war" ],
340 "osgi" => [ "jolokia-osgi", "jolokia-osgi-%v.jar", "jolokia.jar" ],
341 "osgi-bundle" => [ "jolokia-osgi-bundle", "jolokia-osgi-bundle-%v.jar", "jolokia-bundle.jar" ],
342 "mule" => [ "jolokia-mule", "jolokia-mule-%v.jar", "jolokia-mule.jar" ],
343 "jdk6" => [ "jolokia-jvm-jdk6", "jolokia-jvm-jdk6-%v-agent.jar", "jolokia.jar" ]
344 },
345 templates => {
346 "jolokia-access.xml" => "http://www.jolokia.org/templates/jolokia-access.xml"
347 }
348 };
349 }
350  
351  
352 1;
353  
354 =head1 LICENSE
355  
356 This file is part of jmx4perl.
357 Jmx4perl is free software: you can redistribute it and/or modify
358 it under the terms of the GNU General Public License as published by
359 The Free Software Foundation, either version 2 of the License, or
360 (at your option) any later version.
361
362 jmx4perl is distributed in the hope that it will be useful,
363 but WITHOUT ANY WARRANTY; without even the implied warranty of
364 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
365 GNU General Public License for more details.
366
367 You should have received a copy of the GNU General Public License
368 along with jmx4perl. If not, see <http://www.gnu.org/licenses/>.
369  
370 A commercial license is available as well. Please contact roland@cpan.org for
371 further details.
372  
373 =head1 AUTHOR
374  
375 roland@cpan.org
376  
377 =cut
378  
379 1;