| 1 | package Nginx::Runner; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use 5.008_001; | ||
| 6 | |||
| 7 | our $VERSION = '0.000001_2'; | ||
| 8 | |||
| 9 | use Nginx::Runner::Config; | ||
| 10 | use File::Temp; | ||
| 11 | use Time::HiRes 'usleep'; | ||
| 12 | use IPC::Open3 'open3'; | ||
| 13 | |||
| 14 | require Carp; | ||
| 15 | |||
| 16 | sub new { | ||
| 17 | my ($class, @args) = @_; | ||
| 18 | |||
| 19 | bless { | ||
| 20 | nginx_bin => "/usr/sbin/nginx", | ||
| 21 | error_log => "/tmp/nginx.error", | ||
| 22 | access_log => "/tmp/nginx.access", | ||
| 23 | servers => [], | ||
| 24 | @args | ||
| 25 | }, $class; | ||
| 26 | } | ||
| 27 | |||
| 28 | sub DESTROY { | ||
| 29 | my $self = shift; | ||
| 30 | |||
| 31 | $self->stop if $self->is_running; | ||
| 32 | } | ||
| 33 | |||
| 34 | sub proxy { | ||
| 35 | my ($self, $src, $dst, @args) = @_; | ||
| 36 | |||
| 37 | if (my ($proto, $address) = ($src =~ m{^(\w+)://(.+?)(/.+)?$})) { | ||
| 38 | if ($proto eq 'http') { | ||
| 39 | $src = $address; | ||
| 40 | } | ||
| 41 | elsif ($proto eq 'https') { | ||
| 42 | $src = $address; | ||
| 43 | push @args, [ssl => 'on']; | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | push @{$self->{servers}}, | ||
| 48 | [ server => [ | ||
| 49 | [listen => $src], | ||
| 50 | [location => '/' => [[proxy_pass => "http://$dst"]]], @args | ||
| 51 | ] | ||
| 52 | ]; | ||
| 53 | |||
| 54 | $self; | ||
| 55 | } | ||
| 56 | |||
| 57 | sub is_running { $_[0]->{pid} } | ||
| 58 | |||
| 59 | sub run { | ||
| 60 | my $self = shift; | ||
| 61 | |||
| 62 | return if $self->is_running; | ||
| 63 | |||
| 64 | my ($pid_fh, $pid_fn) = | ||
| 65 | File::Temp::tempfile(UNLINK => 1, SUFFIX => '.pid'); | ||
| 66 | |||
| 67 | my $config = [ | ||
| 68 | [worker_processes => 1], | ||
| 69 | [error_log => $self->{error_log}, "info"], | ||
| 70 | [pid => $pid_fn], | ||
| 71 | [daemon => "on"], | ||
| 72 | [events => [[worker_connections => 1024], [use => "epoll"]]], | ||
| 73 | [http => [[access_log => $self->{access_log}], @{$self->{servers}}]] | ||
| 74 | ]; | ||
| 75 | |||
| 76 | my ($conf_fh, $conf_fn) = | ||
| 77 | File::Temp::tempfile(UNLINK => 1, SUFFIX => '.conf'); | ||
| 78 | $conf_fh->print(Nginx::Runner::Config::encode($config)); | ||
| 79 | $conf_fh->close; | ||
| 80 | |||
| 81 | my ($stdout, $stderr); | ||
| 82 | |||
| 83 | my $pid = | ||
| 84 | open3(undef, $stdout, undef, $self->{nginx_bin} . " -c $conf_fn"); | ||
| 85 | waitpid($pid, 0); | ||
| 86 | |||
| 87 | if ($?) { | ||
| 88 | my @stdout = <$stdout>; | ||
| 89 | die "Unable to run nginx: $stdout[-1]" if $?; | ||
| 90 | } | ||
| 91 | |||
| 92 | undef $pid; | ||
| 93 | while (!($pid = <$pid_fh>)) { usleep 50; } | ||
| 94 | $pid_fh->close; | ||
| 95 | |||
| 96 | $self->{pid} = $pid; | ||
| 97 | } | ||
| 98 | |||
| 99 | sub stop { | ||
| 100 | my $self = shift; | ||
| 101 | |||
| 102 | kill "TERM", delete $self->{pid}; | ||
| 103 | } | ||
| 104 | |||
| 105 | 1; | ||
| 106 | __END__ |