| 1 | package Collectd::Plugins::RedisClient; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Collectd qw( :all ); | ||
| 6 | |||
| 7 | use Redis; | ||
| 8 | |||
| 9 | # ABSTRACT: collectd plugin for reading counters from a redis server | ||
| 10 | our $VERSION = '1.001'; # VERSION | ||
| 11 | |||
| 12 | |||
| 13 | our $prefix = 'redis'; | ||
| 14 | our $server = '127.0.0.1:6379'; | ||
| 15 | our $metrics = { }; | ||
| 16 | |||
| 17 | our $redis; | ||
| 18 | |||
| 19 | sub redis_client_stats_config { | ||
| 20 | my ($ci) = @_; | ||
| 21 | foreach my $item (@{$ci->{'children'}}) { | ||
| 22 | my $key = lc($item->{'key'}); | ||
| 23 | my $val = $item->{'values'}; | ||
| 24 | |||
| 25 | if ($key eq 'server' ) { | ||
| 26 | $server = $val->[0]; | ||
| 27 | } elsif ($key eq 'prefix' ) { | ||
| 28 | $prefix = $val->[0]; | ||
| 29 | } elsif ($key eq 'metric') { | ||
| 30 | $metrics->{$val->[0]} = $val->[1]; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | return 1; | ||
| 34 | } | ||
| 35 | |||
| 36 | sub _connect_redis { | ||
| 37 | if( ! defined $redis ) { | ||
| 38 | $redis = Redis->new( 'server' => $server ); | ||
| 39 | } | ||
| 40 | return $redis; | ||
| 41 | } | ||
| 42 | |||
| 43 | sub redis_client_stats_read { | ||
| 44 | eval { _connect_redis(); }; | ||
| 45 | if( $@ ) { | ||
| 46 | plugin_log(LOG_WARNING, "cant connect to redis: $@"); | ||
| 47 | return 1; | ||
| 48 | } | ||
| 49 | |||
| 50 | foreach my $metric (keys %$metrics) { | ||
| 51 | my $type = $metrics->{$metric}; | ||
| 52 | |||
| 53 | my @keys = $redis->keys( $metric ); | ||
| 54 | if( scalar(@keys) == 0 ) { next; } | ||
| 55 | |||
| 56 | my @values = $redis->mget( @keys ); | ||
| 57 | for( my $i = 0 ; $i < scalar @keys ; $i++ ) { | ||
| 58 | my $vl = { | ||
| 59 | plugin => 'redis_client', | ||
| 60 | plugin_instance => $prefix, | ||
| 61 | type => $type, | ||
| 62 | type_instance => $keys[$i], | ||
| 63 | values => [ $values[$i] ], | ||
| 64 | }; | ||
| 65 | plugin_dispatch_values($vl); | ||
| 66 | } | ||
| 67 | } | ||
| 68 | return 1; | ||
| 69 | } | ||
| 70 | |||
| 71 | plugin_register(TYPE_CONFIG, "RedisClient", "redis_client_stats_config"); | ||
| 72 | plugin_register(TYPE_READ, "RedisClient", "redis_client_stats_read"); | ||
| 73 | |||
| 74 | 1; | ||
| 75 | |||
| 76 | __END__ |