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