root/trunk/lib/Perlbal/BackendHTTP.pm

Revision 821, 24.9 kB (checked in by ask, 6 months ago)

Make Content-Range replies work

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