| 1 | package Helm::Task::patch; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Moose; | ||
| 5 | use Net::OpenSSH; | ||
| 6 | |||
| 7 | extends 'Helm::Task'; | ||
| 8 | |||
| 9 | sub validate { | ||
| 10 | my $self = shift; | ||
| 11 | my $helm = $self->helm; | ||
| 12 | my $extra_options = $helm->extra_options; | ||
| 13 | |||
| 14 | # make sure we have a file and target and that file exists and is readable | ||
| 15 | $helm->die('Missing option: file') unless $extra_options->{file}; | ||
| 16 | $helm->die('Missing option: target') unless $extra_options->{target}; | ||
| 17 | $helm->die('Invalid option: file. File does not exist') unless -e $extra_options->{file}; | ||
| 18 | $helm->die('Invalid option: file. File is not readable') unless -r $extra_options->{file}; | ||
| 19 | } | ||
| 20 | |||
| 21 | sub help { | ||
| 22 | my $self = shift; | ||
| 23 | return <<END; | ||
| 24 | Patch a file on a remote server(s) with a file from the local | ||
| 25 | machine. Takes the following required options: | ||
| 26 | |||
| 27 | --file | ||
| 28 | The name of the patch file on the local machine. | ||
| 29 | |||
| 30 | --target | ||
| 31 | The full path of the file on the remote server(s) that will | ||
| 32 | be patched. | ||
| 33 | END | ||
| 34 | } | ||
| 35 | |||
| 36 | sub execute { | ||
| 37 | my ($self, %args) = @_; | ||
| 38 | my $server = $args{server}; | ||
| 39 | my $ssh = $args{ssh}; | ||
| 40 | my $helm = $self->helm; | ||
| 41 | my $options = $helm->extra_options; | ||
| 42 | my $file = $options->{file}; | ||
| 43 | my $target = $options->{target}; | ||
| 44 | my $sudo = $helm->sudo; | ||
| 45 | my $cmd; | ||
| 46 | |||
| 47 | # first get our patch file over there with a unique name so there are no collisions | ||
| 48 | my $dest = $self->unique_tmp_file(suffix => '.patch'); | ||
| 49 | $helm->log->debug("Trying to scp local file ($file) to $server:$dest"); | ||
| 50 | $ssh->scp_put($file, $dest) || $helm->die("Can't scp file ($file) to server $server: " . $ssh->error); | ||
| 51 | $helm->log->info("File $file copied to $server:$dest"); | ||
| 52 | |||
| 53 | # if we are using sudo, then let's make sure the file is owned by the other user | ||
| 54 | if( $sudo ) { | ||
| 55 | $helm->log->debug("Changing owner of file ($file) to $sudo"); | ||
| 56 | $cmd = "sudo chown $sudo $dest"; | ||
| 57 | $ssh->system({tty => 1}, $cmd) || $helm->die("Can't execute command ($cmd) on server $server: " . $ssh->error); | ||
| 58 | $helm->log->debug("Owner of file ($file) changed to $sudo"); | ||
| 59 | } | ||
| 60 | |||
| 61 | # now patch the file | ||
| 62 | $cmd = "patch $target $dest"; | ||
| 63 | $helm->run_remote_command(command => $cmd, ssh => $ssh); | ||
| 64 | |||
| 65 | # now remove our file so we leave the server clean | ||
| 66 | $cmd = "rm -f $dest"; | ||
| 67 | $helm->run_remote_command(command => $cmd, ssh => $ssh); | ||
| 68 | } | ||
| 69 | |||
| 70 | __PACKAGE__->meta->make_immutable; | ||
| 71 | |||
| 72 | 1; |