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 sub commit { warn "# commit ignored\n"; }
29 require $trigger_path if -e $trigger_path;
33 my $client = Mojo::Client->new;
34 our $json = Mojo::JSON->new;
35 sub info { warn $_[0], " ",$json->encode($_[1]),$/ }
36 sub debug { info "# $_[0]", $_[1] }
39 $client->keep_alive_timeout(90); # couchdb timeout is 60s
43 my $changes_feed = "$url/_changes?feed=continuous;include_docs=true;since=$seq";
44 info 'GET' => $changes_feed;
45 my $tx = $client->build_tx( GET => $changes_feed );
47 my ( $content, $body ) = @_;
49 debug 'BODY' => $body;
51 if ( length($body) == 0 ) {
52 warn "# empty chunk, heartbeat?\n";
56 foreach ( split(/\r?\n/, $body) ) { # we can get multiple documents in one chunk
58 my $change = $json->decode($_);
60 if ( exists $change->{error} ) {
62 } elsif ( exists $change->{last_seq} ) {
63 $seq = $change->{last_seq};
64 } elsif ( $change->{seq} <= $seq ) {
65 info "ERROR: stale" => $change;
66 } elsif ( exists $change->{changes} ) {
68 my $id = $change->{id} || warn "no id?";
69 my $rev = $change->{changes}->[0]->{rev} || warn "no rev?";
70 $seq = $change->{seq} || warn "no seq?";
72 debug 'change' => $change;
74 if ( filter($change) ) {
75 if ( exists $change->{doc}->{trigger}->{active} ) {
76 debug 'trigger.active', $change->{doc}->{trigger}->{active};
78 $change->{doc}->{trigger}->{active} = [ time() ];
80 debug 'TRIGGER start PUT ', $change->{doc};
81 $client->put( "$url/$id" => $json->encode( $change->{doc} ) => sub {
82 my ($client,$tx) = @_;
84 if ( $tx->res->code == 409 ) {
85 info "TRIGGER ABORTED started on another worker? ", $tx->error;
87 info "ERROR ", $tx->error;
90 my $res = $tx->res->json;
91 $change->{doc}->{_rev} = $res->{rev};
93 debug "TRIGGER execute ", $change->{doc};
96 push @{ $change->{doc}->{trigger}->{active} }, time(), 0; # last timestamp
98 $client->put( "$url/$id" => $json->encode( $change->{doc} ) => sub {
99 my ($client,$tx) = @_;
101 info "ERROR", $tx->error;
103 my $res = $tx->res->json;
104 $change->{doc}->{_rev} = $res->{rev};
105 info "TRIGGER finish ", $change->{doc};
113 warn "UNKNOWN", $json->encode($change);
125 die "ERROR ", $json->encode($error) if $error;