| 1 | # $Id: /mirror/gungho/lib/Gungho/Plugin/Apoptosis.pm 31467 2007-11-30T00:42:50.705701Z lestrrat $ | ||
| 2 | # | ||
| 3 | # Copyright (c) 2007 Daisuke Maki <daisuke@endeworks.jp> | ||
| 4 | # All rights reserved, | ||
| 5 | |||
| 6 | package Gungho::Plugin::Apoptosis; | ||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use base qw(Gungho::Plugin); | ||
| 10 | |||
| 11 | __PACKAGE__->mk_accessors('strategy'); | ||
| 12 | |||
| 13 | sub setup | ||
| 14 | { | ||
| 15 | my $self = shift; | ||
| 16 | my $c = shift; | ||
| 17 | $self->next::method(@_); | ||
| 18 | $self->strategy( Gungho::Plugin::Apoptosis::Time->new($self->config) ); | ||
| 19 | $c->register_event( | ||
| 20 | 'dispatch.dispatch_requests' => sub { $self->check_apoptosis(@_) }, | ||
| 21 | ); | ||
| 22 | } | ||
| 23 | |||
| 24 | sub check_apoptosis | ||
| 25 | { | ||
| 26 | my ($self, $event, $c) = @_; | ||
| 27 | |||
| 28 | # Check apoptosis condition. | ||
| 29 | if ($c->is_running && $self->is_time_to_die($c)) { | ||
| 30 | $c->log->info("[APOPTOSIS] Apoptosis condition reached. Waiting for engine to stop"); | ||
| 31 | $c->shutdown("Apoptosis condition reached"); | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | sub is_time_to_die | ||
| 36 | { | ||
| 37 | my ($self, $c) = shift; | ||
| 38 | $self->strategy->is_time_to_die($c); | ||
| 39 | } | ||
| 40 | |||
| 41 | package Gungho::Plugin::Apoptosis::Time; | ||
| 42 | use strict; | ||
| 43 | use warnings; | ||
| 44 | use base qw(Gungho::Base); | ||
| 45 | |||
| 46 | __PACKAGE__->mk_accessors($_) for qw(started timeout); | ||
| 47 | |||
| 48 | sub new | ||
| 49 | { | ||
| 50 | my $class = shift; | ||
| 51 | my $config = shift; | ||
| 52 | |||
| 53 | my $timeout = $config->{time}{timeout} || 0; | ||
| 54 | my $now = time(); | ||
| 55 | bless { | ||
| 56 | started => $now, | ||
| 57 | timeout => $now + $timeout, | ||
| 58 | }, $class; | ||
| 59 | } | ||
| 60 | |||
| 61 | sub is_time_to_die | ||
| 62 | { | ||
| 63 | my ($self, $c) = @_; | ||
| 64 | if ($self->timeout <= time()) { | ||
| 65 | $c->log->info("[APOPTOSIS] Apoptosis condition reached (timeout = " . $self->timeout . ", current time = " . time() . ")"); | ||
| 66 | return 1; | ||
| 67 | } | ||
| 68 | return 0; | ||
| 69 | } | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | __END__ |