|
| 1 | +use Mojolicious::Lite; |
| 2 | +use Mojo::IOLoop::ReadWriteFork; |
| 3 | + |
| 4 | +# NOTE! |
| 5 | +# THIS APPLICATION IS A BAD IDEA. |
| 6 | +# IT SHOULD ONLY SERVER AS AN EXAMPLE. |
| 7 | + |
| 8 | +get '/tail/:name', sub { |
| 9 | + my $self = shift->render_later; |
| 10 | + my $file = '/var/log/' .$self->stash('name'); |
| 11 | + my $fork = Mojo::IOLoop::ReadWriteFork->new; |
| 12 | + |
| 13 | + # The request will end after 15 seconds of inactivity. |
| 14 | + # The line below can be used to increase that timeout, |
| 15 | + # but it is required to make sure we don't run the |
| 16 | + # "tail" process forever. |
| 17 | + # Mojo::IOLoop->stream($self->tx->connection)->timeout(60); |
| 18 | + |
| 19 | + # Make sure the object does not go out of scope |
| 20 | + $self->stash(fork => $fork); |
| 21 | + |
| 22 | + $self->write_chunk("# tail -f $file\n"); |
| 23 | + |
| 24 | + # Make sure we kill "tail" after the request is finished |
| 25 | + # NOTE: This code might be to simple |
| 26 | + $self->on(finish => sub { |
| 27 | + my $self = shift; |
| 28 | + my $fork = $self->stash('fork') or return; |
| 29 | + app->log->debug("Ending tail process"); |
| 30 | + $fork->kill; |
| 31 | + }); |
| 32 | + |
| 33 | + # Write data from "tail" directly to browser |
| 34 | + $fork->on(read => sub { |
| 35 | + my($fork, $buffer) = @_; |
| 36 | + $self->write_chunk($buffer); |
| 37 | + }); |
| 38 | + |
| 39 | + # Start the tail program. |
| 40 | + # "-n50" is just to make sure we have enough data to make the browser |
| 41 | + # display anything. It should work just fine from curl, Mojo::UserAgent, |
| 42 | + # ..., but from chrome, ie, ... we need a big chunk of data before it |
| 43 | + # gets visible. |
| 44 | + $fork->start(program => 'tail', program_args => ['-f', '-n50', $file]); |
| 45 | +}; |
| 46 | + |
| 47 | +app->start; |
0 commit comments