| 1 | # | ||
| 2 | # (c) Jan Gehring <jan.gehring@gmail.com> | ||
| 3 | # | ||
| 4 | # vim: set ts=3 sw=3 tw=0: | ||
| 5 | # vim: set expandtab: | ||
| 6 | |||
| 7 | package Rex::TaskList::Gearman; | ||
| 8 | |||
| 9 | use strict; | ||
| 10 | use warnings; | ||
| 11 | |||
| 12 | use Cwd qw(getcwd); | ||
| 13 | use File::Basename; | ||
| 14 | use Gearman::Client; | ||
| 15 | |||
| 16 | use Rex::TaskList::Base; | ||
| 17 | use Rex::Logger; | ||
| 18 | use JSON::XS; | ||
| 19 | use base qw(Rex::TaskList::Base); | ||
| 20 | |||
| 21 | sub new { | ||
| 22 | my $that = shift; | ||
| 23 | my $proto = ref($that) || $that; | ||
| 24 | my $self = $proto->SUPER::new(@_); | ||
| 25 | |||
| 26 | bless($self, $proto); | ||
| 27 | |||
| 28 | return $self; | ||
| 29 | } | ||
| 30 | |||
| 31 | sub run { | ||
| 32 | my ($self, $task_name, %option) = @_; | ||
| 33 | |||
| 34 | $option{params} ||= { Rex::Args->get }; | ||
| 35 | |||
| 36 | |||
| 37 | my $task = $self->get_task($task_name); | ||
| 38 | my @all_server = @{ $task->server }; | ||
| 39 | |||
| 40 | my $client = Gearman::Client->new; | ||
| 41 | my $conf = eval eval { local(@ARGV, $/) = ("client.conf"); <>; }; | ||
| 42 | |||
| 43 | if($@) { | ||
| 44 | print "Error parsing configuration file.\n"; | ||
| 45 | print $@ . "\n"; | ||
| 46 | CORE::exit 1; | ||
| 47 | } | ||
| 48 | |||
| 49 | Rex::Logger::debug("Found worker servers: " . join(", ", @{ $conf->{job_servers} })); | ||
| 50 | |||
| 51 | $client->job_servers(@{ $conf->{job_servers} }); | ||
| 52 | my $taskset = $client->new_task_set; | ||
| 53 | my $func_name = basename(getcwd()); | ||
| 54 | Rex::Logger::debug("Using func_name: $func_name"); | ||
| 55 | |||
| 56 | for my $server (@all_server) { | ||
| 57 | |||
| 58 | my $options = { | ||
| 59 | task => $task_name, | ||
| 60 | server => $server->to_s, | ||
| 61 | argv => \@ARGV, | ||
| 62 | options => \%option, | ||
| 63 | in_transaction => $self->is_transaction, | ||
| 64 | default_auth => $self->is_default_auth, | ||
| 65 | }; | ||
| 66 | |||
| 67 | Rex::Logger::info("Adding new task to execute $task_name on $server->to_s"); | ||
| 68 | $taskset->add_task( | ||
| 69 | $func_name => encode_json($options), { | ||
| 70 | on_complete => sub { | ||
| 71 | Rex::Logger::info("Successfully executed task on $server"); | ||
| 72 | }, # nothing yet | ||
| 73 | on_fail => sub { | ||
| 74 | Rex::Logger::info("Error executing task on $server"); | ||
| 75 | }, | ||
| 76 | } | ||
| 77 | ); | ||
| 78 | |||
| 79 | |||
| 80 | } | ||
| 81 | |||
| 82 | Rex::Logger::debug("Waiting for children to finish"); | ||
| 83 | |||
| 84 | $taskset->wait; | ||
| 85 | |||
| 86 | } | ||
| 87 | |||
| 88 | 1; |