| 1 | package App::CSE::Command::Unwatch; | ||
| 2 | $App::CSE::Command::Unwatch::VERSION = '0.016'; | ||
| 3 | use Moose; | ||
| 4 | extends qw/App::CSE::Command/; | ||
| 5 | with qw/App::CSE::Role::DirIndex/; | ||
| 6 | |||
| 7 | use File::MimeInfo::Magic; | ||
| 8 | |||
| 9 | |||
| 10 | use Log::Log4perl; | ||
| 11 | my $LOGGER = Log::Log4perl->get_logger(); | ||
| 12 | |||
| 13 | |||
| 14 | sub execute{ | ||
| 15 | my ($self) = @_; | ||
| 16 | |||
| 17 | my $colorizer = $self->cse()->colorizer(); | ||
| 18 | my $colored = sub{ $colorizer->colored(@_);}; | ||
| 19 | |||
| 20 | my $cse = $self->cse(); | ||
| 21 | |||
| 22 | |||
| 23 | my $previous_pid = $cse->index_meta()->{'watcher.pid'}; | ||
| 24 | unless( $previous_pid ){ | ||
| 25 | $LOGGER->warn("No watcher PID in ".$cse->index_meta_file()." - nothing to do"); | ||
| 26 | return 1; | ||
| 27 | } | ||
| 28 | |||
| 29 | # A previous pid should be a number. | ||
| 30 | ( $previous_pid ) = ( $previous_pid =~ /(\d+)/ ); | ||
| 31 | unless( kill(0, $previous_pid ) ){ | ||
| 32 | $LOGGER->warn(&$colored("Previous watcher (PID=".$previous_pid.") is already dead. Nothing to do", | ||
| 33 | "yellow bold")); | ||
| 34 | delete $self->cse->index_meta()->{'watcher.pid'}; | ||
| 35 | delete $self->cse->index_meta()->{'watcher.start'}; | ||
| 36 | $self->cse->save_index_meta(); | ||
| 37 | return 1; | ||
| 38 | } | ||
| 39 | |||
| 40 | |||
| 41 | kill 15, $previous_pid; | ||
| 42 | my $n_attempts = 4; | ||
| 43 | my $wait_time = 1; | ||
| 44 | while( $n_attempts-- ){ | ||
| 45 | sleep($wait_time); | ||
| 46 | unless( kill(0 , $previous_pid ) ){ | ||
| 47 | $LOGGER->info(&$colored("Watcher PID=$previous_pid has terminated gracefully" , "green bold")); | ||
| 48 | delete $self->cse->index_meta()->{'watcher.pid'}; | ||
| 49 | delete $self->cse->index_meta()->{'watcher.start'}; | ||
| 50 | $self->cse->save_index_meta(); | ||
| 51 | return 0; | ||
| 52 | } | ||
| 53 | $wait_time <<= 1; | ||
| 54 | } | ||
| 55 | |||
| 56 | $LOGGER->error(&$colored("PID=$previous_pid refuses to terminate gracefully. Attempting to kill 9 it", "red bold")); | ||
| 57 | kill 9 , $previous_pid; | ||
| 58 | return 1; | ||
| 59 | } | ||
| 60 | |||
| 61 | __PACKAGE__->meta->make_immutable(); |