fetch (LDAP|CRM)_search from redis
[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         my $sql = "select * from " . $self->param('table');
81         if ( my $username = $self->param('username') ) {
82                 $sql .= " where username = '$username' ";
83         }
84         $sql .= " limit " . ( $self->param('limit') || 1 );
85
86         my $ret = $gearman->req( 'SUBMIT_JOB', 'Store_sql', '', $sql );
87         _render_jsonp( $self, $ret );
88 };
89
90 get '/_g/status' => sub {
91         my $self = shift;
92
93         my $ret = $gearman->req( 'TEXT' => 'status' );
94         warn "# status:\n$ret";
95
96         my @c = qw(function total running available);
97
98         my $status;
99         foreach my $l ( split(/\n/,$ret) ) {
100                 my @v = split(/\t/, $l);
101                 my $h;
102                 $h->{$c[$_]} = $v[$_] foreach 0 .. $#v;
103                 push @$status, $h;
104         }
105         warn "## ", dump $status;
106         _render_jsonp( $self, Mojo::JSON->new->encode({ status => $status }) );
107 };
108
109 sub _gearman_redis {
110         my ( $job, $params, $timeout ) = @_;
111
112         my $key = $params;
113         $key =~ s/\W+/_/gs;
114         $key =~ s/\s+/_/gs;
115         $key = "sql.$key";
116         warn "# _gearman_redis $key [$timeout s]";
117
118         my $redis = Redis->new;
119         my $ret;
120
121         if ( $ret = $redis->get($key) ) {
122                 warn "redis hit $key\n";
123         } else {
124                 $gearman->timeout($timeout);
125                 $ret = $gearman->req( 'SUBMIT_JOB', $job, '', $params );
126                 die "no result for $params" unless $ret;
127
128                 $redis->set($key => $ret);
129         }
130
131         $redis->expire($key => 60); # refresh redis key timeout
132
133         $ret = Mojo::JSON->new->decode( $ret );
134
135         if ( ! exists $ret->{error} && ref $ret->{columns} ne 'ARRAY' ) {
136                 $ret->{error} = 'query run longer than ' . $gearman->timeout . ' s timeout';
137         }
138
139         return $ret;
140 }
141
142 get '/gnuplot' => sub {
143         my $self = shift;
144
145         my $sql = $self->param('sql');
146
147         if ( my $timeout = $self->param('timeout') ) {
148                 warn "set timout to $timeout";
149                 $gearman->timeout( $timeout );
150         } else {
151                 $self->param( timeout => $gearman->timeout );
152         }
153
154         return $self->render('gnuplot', img => '', gnuplot => '') unless $sql;
155
156         # re-format SQL
157         $sql =~ s/\s+(from|where|order|limit|join)/\n$1/gs;
158         $self->param( sql => $sql );
159
160         my $ret = _gearman_redis( 'Store_sql' => $sql, $self->param('timeout') );
161
162         return $self->render('gnuplot', sql => $sql, img => '', gnuplot => $ret->{error} )
163                 if exists $ret->{error};
164
165         my $dir = $self->app->home->rel_dir('public');
166
167         my $name = $sql;
168         $name =~ s/\W+//gs;
169         $name .= '.png';
170
171 warn "# $sql -> $name";
172
173         mkdir "$dir/gnuplot" unless -e "$dir/gnuplot";
174         my $png = "$dir/gnuplot/$name"; # FIXME
175
176         my @c = @{ $ret->{columns} };
177
178         my $gnuplot = qq|
179 set terminal png
180 set output '$png'
181 |;
182
183         my $del; # delimiter between date and time
184
185         if ( $ret->{rows}->[0]->[0] =~ m/(\d{4}-\d{2}-\d{2})(.)?(\d{2}:\d{2}:\d{2})?/ ) {
186
187                 my ( $date,$time );
188                 ( $date, $del, $time ) = ( $1,$2,$3 );
189
190                 my $fmt = '%Y-%m-%d';
191                 $fmt   .= 'T' if $del;
192                 $fmt   .= '%H:%M:%S' if $time;
193
194                 my $format_x = $time ? '%d %H:%M' : '%Y-%m-%d';
195                 $gnuplot .= qq|
196
197 set xdata time
198 set timefmt "$fmt"
199
200 set format x "$format_x"
201 set xtics nomirror rotate by -90
202
203 |;
204
205         } else { 
206                 warn "first column not timestamp";
207         }
208
209         my $plot = 'plot ';
210         my $with = $self->param('with') || 'dots';
211         foreach my $i ( 1 .. $#{ $ret->{rows}->[0] } ) {
212                 $gnuplot .= $plot; $plot = ',';
213                 $gnuplot .= qq| '-' using 1:2 with $with title "$c[$i]" |;
214         }
215         $gnuplot .= "\n";
216
217         foreach my $i ( 1 .. $#{ $ret->{rows}->[0] } ) {
218
219                 foreach my $row ( @{ $ret->{rows} } ) {
220                         my $date = $row->[0];
221                         $date =~ s/\Q$del\E/T/g if $del;
222                         $date =~ s/\.\d+//;
223                         $gnuplot .= join(" ", $date, $row->[$i])."\n";
224                 }
225                 $gnuplot .= "e\n";
226         }
227
228         open(my $fd, '|-', 'gnuplot') || die "gnuplot: $!";
229         print $fd $gnuplot;
230         close($fd);
231
232         $gnuplot = '' unless $self->param('include_gnuplot');
233
234         $self->render('gnuplot', sql => $sql, img => "/gnuplot/$name", gnuplot => $gnuplot);
235 };
236
237 get '/_redis' => sub {
238         my $self = shift;
239
240         _render_jsonp( $self, Mojo::JSON->new->encode({ status => APKPM::Model->redis_status }) );
241 };
242
243 get '/user' => sub {
244         my $self = shift;
245
246         $self->render('user');
247 };
248
249 get '/psql/:command' => sub {
250         my $self = shift;
251         my $command = $self->param('command');
252         $command =~ s/^_/\\/ && warn "internal psql command $command";
253         $command = sprintf "psql -c '%s' apkpm", $command;
254         my $output = `$command`; # FIXME unsecure
255         $self->render_text( "\$ <b><tt>$command</tt></b>\n\n<pre>$output</pre>" );
256 };
257
258 # create pid file
259 open(my $pid, '>', '/tmp/apkpm.web_ui.pid');
260 print $pid "$$\n";
261 close $pid;
262
263 app->start;