root/lang/perl/Moobal/trunk/lib/Moobal/Component/BackendHTTP.pm @ 11971

Revision 11971, 25.1 kB (checked in by daisuke, 5 years ago)

proxy accepts connections, but blocks

  • Property svn:keywords set to Id
Line 
1######################################################################
2# HTTP connection to backend node
3#
4# Copyright 2004, Danga Interactive, Inc.
5# Copyright 2005-2007, Six Apart, Ltd.
6#
7
8package Moobal::Component::BackendHTTP;
9use Moose;
10
11extends 'Moobal::Component::HTTP';
12
13# Moobal::Component::Proxy connection, or undef
14has 'client' => (
15    is => 'rw',
16    isa => 'Moobal::Component::Proxy'
17);
18
19# Moobal::Service
20has 'service' => (
21    is => 'rw',
22    isa => 'Moobal::Service'
23);
24
25# Moobal::Pool; whatever pool we spawned from
26has 'pool' => (
27    is => 'rw',
28    isa => 'Moobal::Pool'
29);
30
31# IP scalar
32has 'ip' => (
33    is => 'rw',
34    isa => 'Str',
35    required => 1,
36);
37
38# port scalar
39has 'port' => (
40    is => 'rw',
41    isa => 'Str',
42    required => 1,
43);
44
45# "$ip:$port"
46has 'ipport' => (
47    is => 'rw',
48    isa => 'Str',
49    required => 1,
50);
51
52# object; must implement reporter interface
53has 'reportto' => (
54    is => 'rw',
55    does => 'Moobal::Role::Reporter'
56);
57
58
59# has been accepted by a webserver and we know for sure we're not just
60# talking to the TCP stack
61has 'has_attention' => (
62    is => 'rw',
63    isa => 'Bool'
64);
65
66# if true, we're waiting for an OPTIONS *
67  # response to determine when we have attention
68has 'waiting_options' => (
69    is => 'rw',
70    isa => 'Bool'
71);
72
73# time this connection will be disconnected,
74# if it's kept-alive and backend told us.
75# otherwise undef for unknown.
76has 'disconnect_at' => (
77    is => 'rw',
78    isa => 'Str',
79);
80
81# The following only apply when the backend server sends
82# a content-length header
83
84# length of document being transferred
85has 'content_length' => (
86    is => 'rw',
87    isa => 'Int'
88);
89
90# bytes remaining to be read
91has 'content_length_remain' => (
92    is => 'rw',
93    isa => 'Int'
94);
95
96# number of requests this backend's been used for
97has 'use_count' => (
98    is => 'rw',
99    isa => 'Int',
100);
101
102# int; counts what generation we were spawned in
103has 'generation' => (
104    is => 'rw',
105    isa => 'Int'
106);
107
108# bool; if on, we're doing a buffered upload transmit
109has 'buffered_upload_mode' => (
110    is => 'rw',
111    isa => 'Bool'
112);
113
114
115use Socket qw(PF_INET IPPROTO_TCP SOCK_STREAM SOL_SOCKET SO_ERROR
116              AF_UNIX PF_UNSPEC
117              );
118use IO::Handle;
119
120use Moobal::Component::Proxy;
121
122# if this is made too big, (say, 128k), then perl does malloc instead
123# of using its slab cache.
124use constant BACKEND_READ_SIZE => 61449;  # 60k, to fit in a 64k slab
125
126# keys set here when an endpoint is found to not support persistent
127# connections and/or the OPTIONS method
128our %NoVerify; # { "ip:port" => next-verify-time }
129our %NodeStats; # { "ip:port" => { ... } }; keep statistics about nodes
130
131# constructor for a backend connection takes a service (pool) that it's
132# for, and uses that service to get its backend IP/port, as well as the
133# client that will be using this backend connection.  final parameter is
134# an options hashref that contains some options:
135#       reportto => object obeying reportto interface
136
137sub _create_socket {
138    my ($c, $ip, $port) = @_;
139
140    my $sock;
141    socket $sock, PF_INET, SOCK_STREAM, IPPROTO_TCP;
142
143    unless ($sock && defined fileno($sock)) {
144        $c->log('crit', "Error creating socket: $!");
145        return undef;
146    }
147    my $inet_aton = Socket::inet_aton($ip);
148    unless ($inet_aton) {
149        $c->log('crit', "inet_aton failed creating socket for $ip");
150        return undef;
151    }
152
153    IO::Handle::blocking($sock, 0);
154    connect $sock, Socket::sockaddr_in($port, $inet_aton);
155
156    return $sock;
157}
158
159around 'new' => sub {
160    my $next = shift;
161    my $class = shift;
162    my %args = @_;
163
164    my $self = $next->($class, %args,
165        ipport => join(':', $args{ip}, $args{port}),
166        socket => _create_socket( $args{context}, $args{ip}, $args{port} )
167    );
168
169
170    $self->state("connecting");
171
172    # setup callback in case we get stuck in connecting land
173    $self->context->register_callback(15, sub {
174        if ($self->socket->state eq 'connecting' || $self->socket->state eq 'verifying_backend') {
175            # shouldn't still be connecting/verifying ~15 seconds after create
176            $self->close('callback_timeout');
177        }
178        return 0;
179    });
180
181    # mark another connection to this ip:port
182    my $data = $NodeStats{$self->ipport};
183    if (! $data) {
184        $data = { attempts => 0, lastattempt => 0 };
185        $NodeStats{$self->ipport} = $data;
186    }
187    $data->{attempts}++;
188    $data->{lastattempt} = $self->{create_time};
189
190    # All backend http components are registered into the global
191    # backend pool
192    $self->context->register_backend( $self );
193
194    return $self;
195};
196
197around 'DESTROY' => sub {
198    my $next = shift;
199    my $self = shift;
200    if (my $context = $self->context) {
201        $context->unregister_backend( $self );
202    }
203    $next->($self, @_ );
204};
205
206sub init {
207    my $self = shift;
208    $self->{req_headers} = undef;
209    $self->{res_headers} = undef;  # defined w/ headers object once all headers in
210    $self->{headers_string} = "";  # blank to start
211    $self->{generation}    = $self->{service}->{generation};
212    $self->{read_size} = 0;        # total bytes read from client
213
214    $self->{client}   = undef;     # Moobal::Component::Proxy object, initially empty
215                                   #    until we ask our service for one
216
217    $self->{has_attention} = 0;
218    $self->{use_count}     = 0;
219    $self->{buffered_upload_mode} = 0;
220}
221
222
223sub new_process {
224    my ($class, $svc, $prog) = @_;
225
226    my ($psock, $csock);
227    socketpair($csock, $psock, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
228        or  die "socketpair: $!";
229
230    $csock->autoflush(1);
231    $psock->autoflush(1);
232
233    my $pid = fork;
234    unless (defined $pid) {
235        warn "fork failed: $!\n";
236        return undef;
237    }
238
239    # child process
240    unless ($pid) {
241        close(STDIN);
242        close(STDOUT);
243        #close(STDERR);
244        open(STDIN, '<&', $psock);
245        open(STDOUT, '>&', $psock);
246        #open(STDERR, ">/dev/null");
247        exec $prog;
248    }
249
250    close($psock);
251    my $sock = $csock;
252
253    my $self = fields::new($class);
254    $self->SUPER::new($sock);
255    Moobal::objctor($self);
256
257    $self->{ipport}   = $prog; # often used as key
258    $self->{service}  = $svc; # the service we're serving for
259    $self->{reportto} = $svc; # reportto interface (same as service)
260    $self->state("connecting");
261
262    $self->init;
263    $self->watch_write(1);
264    return $self;
265}
266
267sub close {
268    my $self = shift; # Moobal::Component::BackendHTTP
269
270    # OSX Gives EPIPE on bad connects, and doesn't fail the connect
271    # so lets treat EPIPE as a event_err so the logic there does
272    # the right thing
273    if (defined $_[0] && $_[0] eq 'EPIPE') {
274        $self->event_err;
275        return;
276    }
277
278    # don't close twice
279    return if $self->{closed};
280
281    # this closes the socket and sets our closed flag
282    $self->SUPER::close(@_);
283
284    # tell our client that we're gone
285    if (my $client = $self->{client}) {
286        $client->backend(undef);
287        $self->{client} = undef;
288    }
289
290    # tell our owner that we're gone
291    if (my $reportto = $self->{reportto}) {
292        $reportto->note_backend_close($self);
293        $self->{reportto} = undef;
294    }
295}
296
297# return our defined generation counter with no parameter,
298# or set our generation if given a parameter
299sub generation {
300    my Moobal::Component::BackendHTTP $self = $_[0];
301    return $self->{generation} unless $_[1];
302    return $self->{generation} = $_[1];
303}
304
305# return what ip and port combination we're using
306sub ipport {
307    my Moobal::Component::BackendHTTP $self = $_[0];
308    return $self->{ipport};
309}
310
311# called to tell backend that the client has gone on to do something else now.
312sub forget_client {
313    my Moobal::Component::BackendHTTP $self = $_[0];
314    $self->{client} = undef;
315}
316
317# called by service when it's got a client for us, or by ourselves
318# when we asked for a client.
319# returns true if client assignment was accepted.
320sub assign_client {
321    my $self = shift; # Moobal::Component::BackendHTTP
322    my Moobal::Component::Proxy $client = shift;
323    return 0 if $self->{client};
324
325    my $svc = $self->{service};
326
327    # set our client, and the client's backend to us
328    $svc->mark_node_used($self->{ipport});
329    $self->{client} = $client;
330    $self->state("sending_req");
331    $self->{client}->backend($self);
332
333    my $hds = $client->{req_headers}->clone;# Moobal::HTTPHeaders
334    $self->{req_headers} = $hds;
335
336    my $client_ip = $client->peer_ip_string;
337
338    # I think I've seen this be undef in practice.  Double-check
339    unless ($client_ip) {
340        warn "Undef client_ip ($client) in assign_client.  Closing.";
341        $client->close;
342        return 0;
343    }
344
345    # Use HTTP/1.0 to backend (FIXME: use 1.1 and support chunking)
346    $hds->set_version("1.0");
347
348    my $persist = $svc->{persist_backend};
349
350    $hds->header("Connection", $persist ? "keep-alive" : "close");
351
352    if ($svc->{enable_reproxy}) {
353        $hds->header("X-Proxy-Capabilities", "reproxy-file");
354    }
355
356    # decide whether we trust the upstream or not, to give us useful
357    # forwarding info headers
358    if ($svc->trusted_ip($client_ip)) {
359        # yes, we trust our upstream, so just append our client's IP
360        # to the existing list of forwarded IPs, if we're a blind proxy
361        # then don't append our IP to the end of the list.
362        unless ($svc->{blind_proxy}) {
363            my @ips = split /,\s*/, ($hds->header("X-Forwarded-For") || '');
364            $hds->header("X-Forwarded-For", join ", ", @ips, $client_ip);
365        }
366    } else {
367        # no, don't trust upstream (untrusted client), so remove all their
368        # forwarding headers and tag their IP as the x-forwarded-for
369        $hds->header("X-Forwarded-For", $client_ip);
370        $hds->header("X-Host", undef);
371        $hds->header("X-Forwarded-Host", undef);
372    }
373
374    $self->tcp_cork(1);
375    $client->state('backend_req_sent');
376
377    $self->{content_length} = undef;
378    $self->{content_length_remain} = undef;
379
380    # run hooks
381    return 1 if $svc->run_hook('backend_client_assigned', $self);
382
383    # now cleanup the headers before we send to the backend
384    $svc->munge_headers($hds) if $svc;
385
386    $self->write($hds->to_string_ref);
387    $self->write(sub {
388        $self->tcp_cork(0);
389        if (my $client = $self->{client}) {
390            # start waiting on a reply
391            $self->watch_read(1);
392            $self->state("wait_res");
393            $client->state('wait_res');
394            $client->backend_ready($self);
395        }
396    });
397
398    return 1;
399}
400
401# called by ClientProxy after we tell it our backend is ready and
402# it has an upload ready on disk
403sub invoke_buffered_upload_mode {
404    my $self = shift; # Moobal::Component::BackendHTTP
405
406    # so, we're receiving a buffered upload, we need to go ahead and
407    # start the buffered upload retransmission to backend process. we
408    # have to turn watching for writes on, since that's what is doing
409    # the triggering, NOT the normal client proxy watch for read
410    $self->{buffered_upload_mode} = 1;
411    $self->watch_write(1);
412}
413
414# Backend
415sub event_write {
416    my $self = shift;
417    print "Backend $self is writeable!\n" if &Moobal::DEBUG >= 2;
418
419    my $ipport = $self->ipport;
420    my $now = time();
421    delete $NoVerify{$ipport} if
422        defined $NoVerify{$ipport} &&
423        $NoVerify{$ipport} < $now;
424
425    if (! $self->{client} && $self->state eq "connecting") {
426        # not interested in writes again until something else is
427        $self->watch_write(0);
428        $NodeStats{$ipport}->{connects}++;
429        $NodeStats{$ipport}->{lastconnect} = $now;
430
431        # OSX returns writeable even if the connect fails
432        # so explicitly check for the error
433        # TODO: make a smaller test case and show to the world
434        if (my $error = unpack('i', getsockopt($self->socket, SOL_SOCKET, SO_ERROR))) {
435            $self->event_err;
436            return;
437        }
438
439        my $service = $self->service;
440        if (defined $service && $service->param('verify_backend') &&
441            !$self->{has_attention} && !defined $NoVerify{$ipport}) {
442
443            # the backend should be able to answer this incredibly quickly.
444            $self->write("OPTIONS " . ($service->param('verify_backend_path') || '/') . " HTTP/1.0\r\nConnection: keep-alive\r\n\r\n");
445            $self->watch_read(1);
446            $self->{waiting_options} = 1;
447            $self->{content_length_remain} = undef;
448            $self->state("verifying_backend");
449        } else {
450            # register our boredom (readiness for a client/request)
451            $self->state("bored");
452            $self->register_boredom();
453        }
454        return;
455    }
456
457    # if we have a client, and we're currently doing a buffered upload
458    # sendfile, then tell the client to continue sending us data
459    if ($self->{client} && $self->{buffered_upload_mode}) {
460        $self->{client}->continue_buffered_upload($self);
461        return;
462    }
463
464    my $done = $self->write(undef);
465    $self->watch_write(0) if $done;
466}
467
468sub verify_failure {
469    my $self = shift; # Moobal::Component::BackendHTTP
470    $NoVerify{$self->{ipport}} = time() + 60;
471    $self->{reportto}->note_bad_backend_connect($self);
472    $self->close('no_keep_alive');
473    return;
474}
475
476sub event_read_waiting_options { # : void
477    my $self = shift; # Moobal::Component::BackendHTTP
478    if ($self->{content_length_remain}) {
479        # the HTTP/1.1 spec says OPTIONS responses can have content-lengths,
480        # but the meaning of the response is reserved for a future spec.
481        # this just gobbles it up for.
482        my $bref = $self->read(BACKEND_READ_SIZE);
483        return $self->verify_failure unless defined $bref;
484        $self->{content_length_remain} -= length($$bref);
485    } elsif (my $hd = $self->read_response_headers) {
486        # see if we have keep alive support
487        return $self->verify_failure unless $hd->res_keep_alive_options;
488        $self->{content_length_remain} = $hd->header("Content-Length");
489    }
490
491    # if we've got the option response and read any response data
492    # if present:
493    if ($self->{res_headers} && ! $self->{content_length_remain}) {
494        # other setup to mark being done with options checking
495        $self->{waiting_options} = 0;
496        $self->{has_attention} = 1;
497        $NodeStats{$self->{ipport}}->{verifies}++;
498        $self->next_request(1); # initial
499    }
500    return;
501}
502
503sub handle_response { # : void
504    my $self = shift; # Moobal::Component::BackendHTTP
505    my $hd = $self->{res_headers}; # Moobal::HTTPHeaders
506    my $client = $self->{client}; # Moobal::Component::Proxy
507
508    print "BackendHTTP: handle_response\n" if &Moobal::DEBUG >= 2;
509
510    my $res_code = $hd->response_code;
511
512    # keep a rolling window of the last 500 response codes
513    my $ref = ($NodeStats{$self->{ipport}}->{responsecodes} ||= []);
514    push @$ref, $res_code;
515    if (scalar(@$ref) > 500) {
516        shift @$ref;
517    }
518
519    # call service response received function
520    return if $self->{reportto}->backend_response_received($self);
521
522    # standard handling
523    $self->state("xfer_res");
524    $client->state("xfer_res");
525    $self->{has_attention} = 1;
526
527    # RFC 2616, Sec 4.4: Messages MUST NOT include both a
528    # Content-Length header field and a non-identity
529    # transfer-coding. If the message does include a non-
530    # identity transfer-coding, the Content-Length MUST be
531    # ignored.
532    my $te = $hd->header("Transfer-Encoding");
533    if ($te && $te !~ /\bidentity\b/i) {
534        $hd->header("Content-Length", undef);
535    }
536
537    my $rqhd = $self->{req_headers}; # Moobal::HTTPHeaders
538
539    # setup our content length so we know how much data to expect, in general
540    # we want the content-length from the response, but if this was a head request
541    # we know it's a 0 length message the client wants
542    if ($rqhd->request_method eq 'HEAD') {
543        $self->{content_length} = 0;
544    } else {
545        $self->{content_length} = $hd->content_length;
546    }
547    $self->{content_length_remain} = $self->{content_length} || 0;
548
549    my $reproxy_cache_for = $hd->header('X-REPROXY-CACHE-FOR') || 0;
550
551    # special cases:  reproxying and retrying after server errors:
552    if ((my $rep = $hd->header('X-REPROXY-FILE')) && $self->may_reproxy) {
553        # make the client begin the async IO while we move on
554        $client->start_reproxy_file($rep, $hd);
555        $self->next_request;
556        return;
557    } elsif ((my $urls = $hd->header('X-REPROXY-URL')) && $self->may_reproxy) {
558        $self->{service}->add_to_reproxy_url_cache($rqhd, $hd)
559            if $reproxy_cache_for;
560        $client->start_reproxy_uri($self->{res_headers}, $urls);
561        $self->next_request;
562        return;
563    } elsif ((my $svcname = $hd->header('X-REPROXY-SERVICE')) && $self->may_reproxy) {
564        $self->{client} = undef;
565        $client->start_reproxy_service($self->{res_headers}, $svcname);
566        $self->next_request;
567        return;
568    } elsif ($res_code == 500 &&
569             $rqhd->request_method =~ /^GET|HEAD$/ &&
570             $client->should_retry_after_500($self)) {
571        # eh, 500 errors are rare.  just close and don't spend effort reading
572        # rest of body's error message to no client.
573        $self->close;
574
575        # and tell the client to try again with a new backend
576        $client->retry_after_500($self->{service});
577        return;
578    }
579
580    # regular path:
581    my $res_source = $client->{primary_res_hdrs} || $hd;
582    my $thd = $client->{res_headers} = $res_source->clone;
583
584    # setup_keepalive will set Connection: and Keep-Alive: headers for us
585    # as well as setup our HTTP version appropriately
586    $client->setup_keepalive($thd);
587
588    # if we had an alternate primary response header, make sure
589    # we send the real content-length (from the reproxied URL)
590    # and not the one the first server gave us
591    if ($client->{primary_res_hdrs}) {
592        $thd->header('Content-Length', $hd->header('Content-Length'));
593        $thd->header('X-REPROXY-FILE', undef);
594        $thd->header('X-REPROXY-URL', undef);
595        $thd->header('X-REPROXY-EXPECTED-SIZE', undef);
596        $thd->header('X-REPROXY-CACHE-FOR', undef);
597
598        # also update the response code, in case of 206 partial content
599        my $rescode = $hd->response_code;
600        $thd->code($rescode) if $rescode == 206 || $rescode == 416;
601        $thd->code(200) if $thd->response_code == 204;  # upgrade HTTP No Content (204) to 200 OK.
602    }
603
604    print "  writing response headers to client\n" if &Moobal::DEBUG >= 3;
605    $client->write($thd->to_string_ref);
606
607    print("  content_length=", (defined $self->{content_length} ? $self->{content_length} : "(undef)"),
608          "  remain=",         (defined $self->{content_length_remain} ? $self->{content_length_remain} : "(undef)"), "\n")
609        if &Moobal::DEBUG >= 3;
610
611    if (defined $self->{content_length} && ! $self->{content_length_remain}) {
612        print "  done.  detaching.\n" if &Moobal::DEBUG >= 3;
613        # order important:  next_request detaches us from client, so
614        # $client->close can't kill us
615        $self->next_request;
616        $client->write(sub {
617            $client->backend_finished;
618        });
619    }
620}
621
622sub may_reproxy {
623    my $self = shift; # Moobal::Component::BackendHTTP
624    my $svc = $self->{service}; # Moobal::Service
625    return 0 unless $svc;
626    return $svc->{enable_reproxy};
627}
628
629# Backend
630sub event_read {
631    my $self = shift; # Moobal::Component::BackendHTTP
632    print "Backend $self is readable!\n" if &Moobal::DEBUG >= 2;
633
634    return $self->event_read_waiting_options if $self->{waiting_options};
635
636    my $client = $self->{client}; # Moobal::Component::Proxy
637
638    # with persistent connections, sometimes we have a backend and
639    # no client, and backend becomes readable, either to signal
640    # to use the end of the stream, or because a bad request error,
641    # which I can't totally understand.  in any case, we have
642    # no client so all we can do is close this backend.
643    return $self->close('read_with_no_client') unless $client;
644
645    unless ($self->{res_headers}) {
646        return unless $self->read_response_headers;
647        return $self->handle_response;
648    }
649
650    # if our client's behind more than the max limit, stop buffering
651    if ($client->too_far_behind_backend) {
652        $self->watch_read(0);
653        $client->{backend_stalled} = 1;
654        return;
655    }
656
657    my $bref = $self->read(BACKEND_READ_SIZE);
658
659    if (defined $bref) {
660        $client->write($bref);
661
662        # HTTP/1.0 keep-alive support to backend.  we just count bytes
663        # until we hit the end, then we know we can send another
664        # request on this connection
665        if ($self->{content_length}) {
666            $self->{content_length_remain} -= length($$bref);
667            if (! $self->{content_length_remain}) {
668                # order important:  next_request detaches us from client, so
669                # $client->close can't kill us
670                $self->next_request;
671                $client->write(sub { $client->backend_finished; });
672            }
673        }
674        return;
675    } else {
676        # backend closed
677        print "Backend $self is done; closing...\n" if &Moobal::DEBUG >= 1;
678
679        $client->backend(undef);    # disconnect ourselves from it
680        $self->{client} = undef;    # .. and it from us
681        $self->close('backend_disconnect'); # close ourselves
682
683        $client->write(sub { $client->backend_finished; });
684        return;
685    }
686}
687
688# if $initial is on, then don't increment use count
689sub next_request {
690    my Moobal::Component::BackendHTTP $self = $_[0];
691    my $initial = $_[1];
692
693    # don't allow this if we're closed
694    return if $self->{closed};
695
696    # set alive_time so reproxy can intelligently reuse this backend
697    my $now = time();
698    $self->{alive_time} = $now;
699    $NodeStats{$self->{ipport}}->{requests}++ unless $initial;
700    $NodeStats{$self->{ipport}}->{lastresponse} = $now;
701
702    my $hd = $self->{res_headers};  # response headers
703
704    # verify that we have keep-alive support.  by passing $initial to res_keep_alive,
705    # we signal that req_headers may be undef (if we just did an options request)
706    return $self->close('next_request_no_persist')
707        unless $hd->res_keep_alive($self->{req_headers}, $initial);
708
709    # and now see if we should closed based on the pool we're from
710
711    my $pool = $self->pool;
712    return $self->close('pool_requested_closure')
713        if $pool && ! $pool->backend_should_live($self);
714
715    # we've been used
716    $self->{use_count}++ unless $initial;
717
718    # service specific
719    if (my $svc = $self->{service}) { # Moobal::Service 
720        # keep track of how many times we've been used, and don't
721        # keep using this connection more times than the service
722        # is configured for.
723        if ($svc->{max_backend_uses} && ($self->{use_count} > $svc->{max_backend_uses})) {
724            return $self->close('exceeded_max_uses');
725        }
726    }
727
728    # if backend told us, keep track of when the backend
729    # says it's going to boot us, so we don't use it within
730    # a few seconds of that time
731    if (($hd->header("Keep-Alive") || '') =~ /\btimeout=(\d+)/i) {
732        $self->{disconnect_at} = $now + $1;
733    } else {
734        $self->{disconnect_at} = undef;
735    }
736
737    $self->{client} = undef;
738
739    $self->state("bored");
740    $self->watch_write(0);
741
742    $self->{req_headers} = undef;
743    $self->{res_headers} = undef;
744    $self->{headers_string} = "";
745    $self->{req_headers} = undef;
746
747    $self->{read_size} = 0;
748    $self->{content_length_remain} = undef;
749    $self->{content_length} = undef;
750    $self->{buffered_upload_mode} = 0;
751
752    $self->{reportto}->register_boredom($self);
753    return;
754}
755
756# Backend: bad connection to backend
757sub event_err {
758    my $self = shift; # Moobal::Component::BackendHTTP
759
760    # FIXME: we get this after backend is done reading and we disconnect,
761    # hence the misc checks below for $self->{client}.
762
763    print "BACKEND event_err\n" if
764        &Moobal::DEBUG >= 2;
765
766    if ($self->{client}) {
767        # request already sent to backend, then an error occurred.
768        # we don't want to duplicate POST requests, so for now
769        # just fail
770        # TODO: if just a GET request, retry?
771        $self->{client}->close('backend_error');
772        $self->close('error');
773        return;
774    }
775
776    if ($self->{state} eq "connecting" ||
777        $self->{state} eq "verifying_backend") {
778        # then tell the service manager that this connection
779        # failed, so it can spawn a new one and note the dead host
780        $self->{reportto}->note_bad_backend_connect($self, 1);
781    }
782
783    # close ourselves first
784    $self->close("error");
785}
786
787# Backend
788sub event_hup {
789    my $self = shift; # Moobal::Component::BackendHTTP
790    print "HANGUP for $self\n" if &Moobal::DEBUG;
791    $self->close("after_hup");
792}
793
794sub as_string {
795    my $self = shift; # Moobal::Component::BackendHTTP
796
797    my $ret = $self->SUPER::as_string;
798    my $name = $self->{sock} ? getsockname($self->{sock}) : undef;
799    my $lport = $name ? (Socket::sockaddr_in($name))[0] : undef;
800    $ret .= ": localport=$lport" if $lport;
801    if (my Moobal::Component::Proxy $cp = $self->{client}) {
802        $ret .= "; client=$cp->{fd}";
803    }
804    $ret .= "; uses=$self->{use_count}; $self->{state}";
805    if (defined $self->{service} && $self->{service}->{verify_backend}) {
806        $ret .= "; has_attention=";
807        $ret .= $self->{has_attention} ? 'yes' : 'no';
808    }
809
810    return $ret;
811}
812
813sub die_gracefully {
814    # see if we need to die
815    my $self = shift; # Moobal::Component::BackendHTTP
816    $self->close('graceful_death') if $self->state eq 'bored';
817}
818
8191;
820
821# Local Variables:
822# mode: perl
823# c-basic-indent: 4
824# indent-tabs-mode: nil
825# End:
Note: See TracBrowser for help on using the browser.