3 # back-end trigger server for CouchDB monitoring changes feed:
5 # http://wiki.apache.org/couchdb/HTTP_database_API#Changes
7 # implements state machine using document which you cen put with:
9 # curl -X PUT http://localhost:5984/monitor/df -d '{"trigger":{"command":"df -P","format":"table"}}'
11 # DEFAULT TRIGGER EXECUTE SHELL COMMANDS. IT IS NOT SECURE IF YOUR COUCHDB ISN'T SECURE!
16 use lib 'common/mojo/lib';
20 use Time::HiRes qw(time);
21 use Data::Dump qw(dump);
23 my ( $url, $trigger_path ) = @ARGV;
25 $url ||= 'http://localhost:5984/monitor';
26 $trigger_path ||= 'trigger/shell.pm' ;
28 our $database = $1 if $url =~ m{/(\w+)/?$};
30 sub commit { warn "# commit ignored\n"; }
31 require $trigger_path if -e $trigger_path;
35 my $client = Mojo::Client->new;
36 our $json = Mojo::JSON->new;
37 sub info { warn $_[0], " ",$json->encode($_[1]),$/ }
38 sub debug { info "# $_[0]", $_[1] }
41 $client->keep_alive_timeout(90); # couchdb timeout is 60s
45 my $changes_feed = "$url/_changes?feed=continuous;include_docs=true;since=$seq";
46 info 'GET' => $changes_feed;
47 my $tx = $client->build_tx( GET => $changes_feed );
49 my ( $content, $body ) = @_;
51 return if length($body) == 0; # empty chunk, heartbeat?
53 debug 'BODY' => $body;
55 foreach ( split(/\r?\n/, $body) ) { # we can get multiple documents in one chunk
57 my $change = $json->decode($_);
59 if ( exists $change->{error} ) {
61 } elsif ( exists $change->{last_seq} ) {
62 $seq = $change->{last_seq};
63 } elsif ( $change->{seq} <= $seq ) {
64 info "ERROR: stale" => $change;
65 } elsif ( exists $change->{changes} ) {
67 my $id = $change->{id} || warn "no id?";
68 my $rev = $change->{changes}->[0]->{rev} || warn "no rev?";
69 $seq = $change->{seq} || warn "no seq?";
71 debug 'change' => $change;
73 if ( filter($change) ) {
74 if ( exists $change->{doc}->{trigger}->{active} ) {
75 debug 'trigger.active', $change->{doc}->{trigger}->{active};
77 $change->{doc}->{trigger}->{active} = [ time() ];
79 debug 'TRIGGER start PUT ', $change->{doc};
80 $client->put( "$url/$id" => $json->encode( $change->{doc} ) => sub {
81 my ($client,$tx) = @_;
83 if ( $tx->res->code == 409 ) {
84 info "TRIGGER ABORTED started on another worker? ", $tx->error;
86 info "ERROR $url/$id ", $tx->error;
89 my $res = $tx->res->json;
90 $change->{doc}->{_rev} = $res->{rev};
92 debug "TRIGGER execute ", $change->{doc};
95 push @{ $change->{doc}->{trigger}->{active} }, time(), 0; # last timestamp
97 $client->put( "$url/$id" => $json->encode( $change->{doc} ) => sub {
98 my ($client,$tx) = @_;
100 info "ERROR $url/$id", $tx->error;
102 my $res = $tx->res->json;
103 $change->{doc}->{_rev} = $res->{rev};
104 info "TRIGGER finish ", $change->{doc};
112 warn "UNKNOWN", $json->encode($change);
124 die "ERROR ", $json->encode($error) if $error;