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