Skip to content

Commit

Permalink
added heartbeat event to Mojo::Server::Prefork
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Jan 16, 2013
1 parent 33f97a5 commit c3c0c46
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
13 changes: 11 additions & 2 deletions lib/Mojo/Server/Prefork.pm
Expand Up @@ -83,7 +83,7 @@ sub _heartbeat {
return unless $self->{reader}->sysread(my $chunk, 4194304);

# Update heartbeats
$self->{pool}{$1} and $self->{pool}{$1}{time} = time
$self->{pool}{$1} and $self->emit(heartbeat => $1)->{pool}{$1}{time} = time
while $chunk =~ /(\d+)\n/g;
}

Expand Down Expand Up @@ -320,10 +320,19 @@ can emit the following new ones.
Emitted when the server shuts down.
=head2 heartbeat
$prefork->on(heartbeat => sub {
my ($prefork, $pid) = @_;
...
});
Emitted when a heartbeat message has been received from a worker.
=head2 manage
$prefork->on(manage => sub {
my $prefork = shift;
my ($prefork, $pid) = @_;
...
});
Expand Down
31 changes: 18 additions & 13 deletions t/mojo/prefork.t
Expand Up @@ -11,27 +11,31 @@ use Test::More;
plan skip_all => 'set TEST_PREFORK to enable this test (developer only!)'
unless $ENV{TEST_PREFORK};

use List::Util 'first';
use Mojo::IOLoop;
use Mojo::Server::Prefork;
use Mojo::UserAgent;
use Mojolicious::Lite;

# Silence
app->log->level('fatal');

get '/' => {text => 'just works!'};

# Basic functionality
my $port = Mojo::IOLoop->generate_port;
my $prefork
= Mojo::Server::Prefork->new(app => app, listen => ["http://*:$port"]);
my $prefork = Mojo::Server::Prefork->new(listen => ["http://*:$port"]);
$prefork->unsubscribe('request');
$prefork->on(
request => sub {
my ($prefork, $tx) = @_;
$tx->res->code(200);
$tx->res->body('just works!');
$tx->resume;
}
);
is $prefork->workers, 4, 'start with four workers';
my (@spawn, @reap, $tx, $graceful);
my (@spawn, @reap, $worker, $tx, $graceful);
$prefork->on(spawn => sub { push @spawn, pop });
$prefork->on(
manage => sub {
my $prefork = shift;
$tx = Mojo::UserAgent->new->get("http://localhost:$port");
$prefork->once(
heartbeat => sub {
my ($prefork, $pid) = @_;
$worker = $pid;
$tx = Mojo::UserAgent->new->get("http://localhost:$port");
kill 'QUIT', $$;
}
);
Expand All @@ -40,6 +44,7 @@ $prefork->on(finish => sub { $graceful = pop });
$prefork->run;
is scalar @spawn, 4, 'four workers spawned';
is scalar @reap, 4, 'four workers reaped';
ok !!first { $worker eq $_ } @spawn, 'worker has a heartbeat';
ok $graceful, 'server has been stopped gracefully';
is_deeply [sort @spawn], [sort @reap], 'same process ids';
is $tx->res->code, 200, 'right status';
Expand Down

0 comments on commit c3c0c46

Please sign in to comment.