pass gearman timeout option correctly
[APKPM.git] / web_ui.pl
1 #!/usr/bin/env perl
2
3 use Mojolicious::Lite;
4 use Redis;
5
6 use lib '/srv/MojoX-Gearman/lib';
7 use MojoX::Gearman;
8
9 use lib 'lib';
10 use APKPM::Model;
11
12 use Data::Dump qw(dump);
13
14 plugin 'tag_helpers';
15 # Documentation browser under "/perldoc" (this plugin requires Perl 5.10)
16 plugin 'pod_renderer';
17
18 app->secret('apkpm');
19
20 get '/' => sub {
21         my $self = shift;
22         $self->render('index');
23 };
24
25 get '/ping_http' => sub {
26         my $self = shift;
27         my $gearman = $self->client;
28         my $pong = $gearman->post( "http://localhost:4780/ping" => { Connection => 'close' } => "some data" )->res->body;
29         warn "ping = $pong";
30         $self->render( 'ping', pong => $pong );
31 };
32
33 my $gearman = MojoX::Gearman->new; #( ioloop => Mojo::IOLoop->singleton );
34 $gearman->server( $ENV{GEARMAN} || 'localhost:4730' );
35 $gearman->timeout( 15 );
36
37 get '/ping_g' => sub {
38         my $self = shift;
39         my $pong = $gearman->req( 'SUBMIT_JOB', 'ping', '', "some data 2" );
40         warn "ping = $pong";
41         $self->render( 'ping', pong => $pong );
42 };
43
44 sub _render_jsonp {
45         my ( $self, $json ) = @_;
46         #my $data = $self->render( json => $json, partial => 1 );
47         my $data = $json;
48         if ( my $callback = $self->param('callback') ) {
49                 $data = "$callback($data)";
50         }
51         $self->render( data => $data, format => 'js' );
52 }
53
54
55 get '/g/:call/:args' => [ args => qr/.*/ ] => sub {
56         my $self = shift;
57         my $ret = $gearman->req( 'SUBMIT_JOB', $self->param('call'), '', $self->param('args') );
58         warn $self->param('call'), " = ", dump($ret), "\n";
59         die "no result for ", $self->param('call'), ' args: ', $self->param('args') unless defined $ret;
60         _render_jsonp( $self, $ret );
61 };
62
63 get '/_g/status' => sub {
64         my $self = shift;
65
66         my $ret = $gearman->req( 'TEXT' => 'status' );
67         warn "# status:\n$ret";
68
69         my @c = qw(function total running available);
70
71         my $status;
72         foreach my $l ( split(/\n/,$ret) ) {
73                 my @v = split(/\t/, $l);
74                 my $h;
75                 $h->{$c[$_]} = $v[$_] foreach 0 .. $#v;
76                 push @$status, $h;
77         }
78         warn "## ", dump $status;
79         _render_jsonp( $self, Mojo::JSON->new->encode({ status => $status }) );
80 };
81
82 sub _gearman_redis {
83         my ( $job, $params, $timeout ) = @_;
84
85         my $key = $params;
86         $key =~ s/\W+/_/gs;
87         $key =~ s/\s+/_/gs;
88         $key = "sql.$key";
89         warn "# _gearman_redis $key [$timeout s]";
90
91         my $redis = Redis->new;
92         my $ret;
93
94         if ( $ret = $redis->get($key) ) {
95                 warn "redis hit $key\n";
96         } else {
97                 $gearman->timeout($timeout);
98                 $ret = $gearman->req( 'SUBMIT_JOB', $job, '', $params );
99                 die "no result for $params" unless $ret;
100
101                 $redis->set($key => $ret);
102         }
103
104         $redis->expire($key => 60); # refresh redis key timeout
105
106         $ret = Mojo::JSON->new->decode( $ret );
107
108         if ( ! exists $ret->{error} && ref $ret->{columns} ne 'ARRAY' ) {
109                 $ret->{error} = 'query run longer than ' . $gearman->timeout . ' s timeout';
110         }
111
112         return $ret;
113 }
114
115 get '/gnuplot' => sub {
116         my $self = shift;
117
118         my $sql = $self->param('sql');
119
120         if ( my $timeout = $self->param('timeout') ) {
121                 warn "set timout to $timeout";
122                 $gearman->timeout( $timeout );
123         } else {
124                 $self->param( timeout => $gearman->timeout );
125         }
126
127         return $self->render('gnuplot', img => '', gnuplot => '') unless $sql;
128
129         # re-format SQL
130         $sql =~ s/\s+(from|where|order|limit|join)/\n$1/gs;
131         $self->param( sql => $sql );
132
133         my $ret = _gearman_redis( 'Store_sql' => $sql, $self->param('timeout') );
134
135         return $self->render('gnuplot', sql => $sql, img => '', gnuplot => $ret->{error} )
136                 if exists $ret->{error};
137
138         my $dir = $self->app->home->rel_dir('public');
139
140         my $name = $sql;
141         $name =~ s/\W+//gs;
142         $name .= '.png';
143
144 warn "# $sql -> $name";
145
146         mkdir "$dir/gnuplot" unless -e "$dir/gnuplot";
147         my $png = "$dir/gnuplot/$name"; # FIXME
148
149         my @c = @{ $ret->{columns} };
150
151         my $gnuplot = qq|
152 set terminal png
153 set output '$png'
154 |;
155
156         my $del; # delimiter between date and time
157
158         if ( $ret->{rows}->[0]->[0] =~ m/(\d{4}-\d{2}-\d{2})(.)?(\d{2}:\d{2}:\d{2})?/ ) {
159
160                 my ( $date,$time );
161                 ( $date, $del, $time ) = ( $1,$2,$3 );
162
163                 my $fmt = '%Y-%m-%d';
164                 $fmt   .= 'T' if $del;
165                 $fmt   .= '%H:%M:%S' if $time;
166
167                 my $format_x = $time ? '%d %H:%M' : '%Y-%m-%d';
168                 $gnuplot .= qq|
169
170 set xdata time
171 set timefmt "$fmt"
172
173 set format x "$format_x"
174 set xtics nomirror rotate by -90
175
176 |;
177
178         } else { 
179                 warn "first column not timestamp";
180         }
181
182         my $plot = 'plot ';
183         my $with = $self->param('with') || 'dots';
184         foreach my $i ( 1 .. $#{ $ret->{rows}->[0] } ) {
185                 $gnuplot .= $plot; $plot = ',';
186                 $gnuplot .= qq| '-' using 1:2 with $with title "$c[$i]" |;
187         }
188         $gnuplot .= "\n";
189
190         foreach my $i ( 1 .. $#{ $ret->{rows}->[0] } ) {
191
192                 foreach my $row ( @{ $ret->{rows} } ) {
193                         my $date = $row->[0];
194                         $date =~ s/\Q$del\E/T/g if $del;
195                         $date =~ s/\.\d+//;
196                         $gnuplot .= join(" ", $date, $row->[$i])."\n";
197                 }
198                 $gnuplot .= "e\n";
199         }
200
201         open(my $fd, '|-', 'gnuplot') || die "gnuplot: $!";
202         print $fd $gnuplot;
203         close($fd);
204
205         $gnuplot = '' unless $self->param('include_gnuplot');
206
207         $self->render('gnuplot', sql => $sql, img => "/gnuplot/$name", gnuplot => $gnuplot);
208 };
209
210 get '/_redis' => sub {
211         my $self = shift;
212
213         _render_jsonp( $self, Mojo::JSON->new->encode({ status => APKPM::Model->redis_status }) );
214 };
215
216 get '/user' => sub {
217         my $self = shift;
218
219         $self->render('user');
220 };
221
222 get '/psql/:command' => sub {
223         my $self = shift;
224         my $command = $self->param('command');
225         $command =~ s/^_/\\/ && warn "internal psql command $command";
226         $command = sprintf "psql -c '%s' apkpm", $command;
227         my $output = `$command`; # FIXME unsecure
228         $self->render_text( "\$ <b><tt>$command</tt></b>\n\n<pre>$output</pre>" );
229 };
230
231 # create pid file
232 open(my $pid, '>', '/tmp/apkpm.web_ui.pid');
233 print $pid "$$\n";
234 close $pid;
235
236 app->start;