root/lang/perl/Moobal/trunk/lib/Moobal/Component/Proxy.pm @ 11949

Revision 11949, 50.7 kB (checked in by daisuke, 5 years ago)

more hacks

  • Property svn:keywords set to Id
Line 
1######################################################################
2# HTTP Connection from a reverse proxy client
3#
4# Copyright 2004, Danga Interactive, Inc.
5# Copyright 2005-2007, Six Apart, Ltd.
6#
7package Moobal::Component::Proxy;
8use Moose;
9
10extends 'Moobal::Component::HTTP';
11
12use Moobal::ChunkedUploadState;
13use Moobal::Util;
14
15has 'backend' => (
16    is => 'rw',
17    isa => 'Moobal::Component::BackendHTTP'
18);
19
20has 'spawn_lock' => (
21    is => 'rw',
22    isa => 'Bool',
23    default => 0
24);
25
26has 'pending_connect_count' => (
27    is => 'rw',
28    isa => 'Int',
29    default => 0
30);
31
32has 'bored_backends' => (
33    is => 'rw',
34    isa => 'ArrayRef[Moobal::Component::BackendHTP]',
35    default => sub { [] }
36);
37
38has 'waiting_client_count' => (
39    is => 'rw',
40    isa => 'Int',
41    default => 0
42);
43
44has 'connect_ahead' => (
45    is => 'rw',
46    isa => 'Int',
47    default => 0
48);
49
50my @fields = (
51# use fields (
52            'backend',             # Moobal::Component::BackendHTTP object (or undef if disconnected)
53            'backend_requested',   # true if we've requested a backend for this request
54            'reconnect_count',     # number of times we've tried to reconnect to backend
55            'high_priority',       # boolean; 1 if we are or were in the high priority queue
56            'low_priority',        # boolean; 1 if we are or were in the low priority queue
57            'reproxy_uris',        # arrayref; URIs to reproxy to, in order
58            'reproxy_expected_size', # int: size of response we expect to get back for reproxy
59            'currently_reproxying',  # arrayref; the host info and URI we're reproxying right now
60            'content_length_remain', # int: amount of data we're still waiting for
61            'responded',           # bool: whether we've already sent a response to the user or not
62            'last_request_time',   # int: time that we last received a request
63            'primary_res_hdrs',  # if defined, we are doing a transparent reproxy-URI
64                                 # and the headers we get back aren't necessarily
65                                 # the ones we want.  instead, get most headers
66                                 # from the provided res headers object here.
67            'is_buffering',        # bool; if we're buffering some/all of a request to memory/disk
68            'is_writing',          # bool; if on, we currently have an aio_write out
69            'start_time',          # hi-res time when we started getting data to upload
70            'bufh',                # buffered upload filehandle object
71            'bufilename',          # string; buffered upload filename
72            'bureason',            # string; if defined, the reason we're buffering to disk
73            'buoutpos',            # int; buffered output position
74            'backend_stalled',   # boolean:  if backend has shut off its reads because we're too slow.
75            'unread_data_waiting',  # boolean:  if we shut off reads while we know data is yet to be read from client
76            'chunked_upload_state', # bool/obj:  if processing a chunked upload, Moobal::ChunkedUploadState object, else undef
77            'request_body_length',  # integer:  request's body length, either as-declared,
78                                    #           or calculated after chunked upload is complete
79
80            # for perlbal sending out UDP packets related to upload status (for xmlhttprequest upload bar)
81            'last_upload_packet',  # unixtime we last sent a UDP upload packet
82            'upload_session',      # client's self-generated upload session
83
84            # error-retrying stuff
85            'retry_count',         # number of times we've retried this request so far after getting 500 errors
86            );
87
88use constant READ_SIZE         => 131072;    # 128k, ~common TCP window size?
89use constant READ_AHEAD_SIZE   =>  32768;    # kinda arbitrary.  sum of these two is max stored per connection while waiting for backend.
90use Errno qw( EPIPE ENOENT ECONNRESET EAGAIN );
91use POSIX qw( O_CREAT O_TRUNC O_RDWR O_RDONLY );
92use Time::HiRes qw( gettimeofday tv_interval );
93
94my $udp_sock;
95
96sub new_from_base {
97    my $class = shift;
98    my $cb = shift; # Moobal::ClientHTTPBase
99    Moobal::Util::rebless($cb, $class);
100    $cb->init;
101    $cb->watch_read(1);
102    $cb->handle_request;
103    return $cb;
104}
105
106sub init {
107    my $self = $_[0]; # Moobal::Component::Proxy
108
109    $self->{last_request_time} = 0;
110
111    $self->{backend} = undef;
112    $self->{high_priority} = 0;
113    $self->{low_priority} = 0;
114
115    $self->{responded} = 0;
116    $self->{unread_data_waiting} = 0;
117    $self->{content_length_remain} = undef;
118    $self->{backend_requested} = 0;
119
120    $self->{is_buffering} = 0;
121    $self->{is_writing} = 0;
122    $self->{start_time} = undef;
123    $self->{bufh} = undef;
124    $self->{bufilename} = undef;
125    $self->{buoutpos} = 0;
126    $self->{bureason} = undef;
127    $self->{chunked_upload_state} = undef;
128    $self->{request_body_length} = undef;
129
130    $self->{reproxy_uris} = undef;
131    $self->{reproxy_expected_size} = undef;
132    $self->{currently_reproxying} = undef;
133
134    $self->{retry_count} = 0;
135}
136
137# given a service name, re-request (GET/HEAD only) to that service, even though
138# you've already done a request to your original service
139sub start_reproxy_service {
140    my $self = $_[0]; # Moobal::Component::Proxy
141    my $primary_res_hdrs = $_[1]; # Moobal::HTTPHeaders
142    my $svc_name = $_[2];
143
144    my $svc = $svc_name ? Moobal->service($svc_name) : undef;
145    unless ($svc) {
146        $self->_simple_response(404, "Vhost twiddling not configured for requested pair.");
147        return 1;
148    }
149
150    $self->{backend_requested} = 0;
151    $self->{backend} = undef;
152    $self->{res_headers} = $primary_res_hdrs;
153
154    $svc->adopt_base_client($self);
155}
156
157# call this with a string of space separated URIs to start a process
158# that will fetch the item at the first and return it to the user,
159# on failure it will try the second, then third, etc
160sub start_reproxy_uri {
161    my $self = $_[0]; # Moobal::Component::Proxy
162    my $primary_res_hdrs = $_[1]; # Moobal::HTTPHeaders
163    my $urls = $_[2];
164
165    # at this point we need to disconnect from our backend
166    $self->{backend} = undef;
167
168    # failure if we have no primary response headers
169    return unless $self->{primary_res_hdrs} ||= $primary_res_hdrs;
170
171    # construct reproxy_uri list
172    if (defined $urls) {
173        my @uris = split /\s+/, $urls;
174        $self->{currently_reproxying} = undef;
175        $self->{reproxy_uris} = [];
176        foreach my $uri (@uris) {
177            next unless $uri =~ m!^http://(.+?)(?::(\d+))?(/.*)?$!;
178            push @{$self->{reproxy_uris}}, [ $1, $2 || 80, $3 || '/' ];
179        }
180    }
181
182    # if we get in here and we have currently_reproxying defined, then something
183    # happened and we want to retry that one
184    if ($self->{currently_reproxying}) {
185        unshift @{$self->{reproxy_uris}}, $self->{currently_reproxying};
186        $self->{currently_reproxying} = undef;
187    }
188
189    # if we have no uris in our list now, tell the user 404
190    return $self->_simple_response(503)
191        unless @{$self->{reproxy_uris} || []};
192
193    # set the expected size if we got a content length in our headers
194    if ($primary_res_hdrs && (my $expected_size = $primary_res_hdrs->header('X-REPROXY-EXPECTED-SIZE'))) {
195        $self->{reproxy_expected_size} = $expected_size;
196    }
197
198    # pass ourselves off to the reproxy manager
199    $self->state('wait_backend');
200    Moobal::ReproxyManager::do_reproxy($self);
201}
202
203# called by the reproxy manager when we can't get to our requested backend
204sub try_next_uri {
205    my $self = $_[0]; # Moobal::Component::Proxy
206
207    shift @{$self->{reproxy_uris}};
208    $self->{currently_reproxying} = undef;
209    $self->start_reproxy_uri();
210}
211
212# returns true if this ClientProxy is too many bytes behind the backend
213sub too_far_behind_backend {
214    my $self    = $_[0]; # Moobal::Component::Proxy
215    my $backend = $self->{backend}   or return 0; # Moobal::Component::BackendHTTP
216
217    # if a backend doesn't have a service, it's a
218    # ReproxyManager-created backend, and thus it should use the
219    # 'buffer_size_reproxy_url' parameter for acceptable buffer
220    # widths, and not the regular 'buffer_size'.  this lets people
221    # tune buffers depending on the types of webservers.  (assumption
222    # being that reproxied-to webservers are event-based and it's okay
223    # to tie the up longer in favor of using less buffer memory in
224    # perlbal)
225    my $max_buffer = defined $backend->{service} ?
226        $self->{service}->{buffer_size} :
227        $self->{service}->{buffer_size_reproxy_url};
228
229    return $self->{write_buf_size} > $max_buffer;
230}
231
232# this is a callback for when a backend has been created and is
233# ready for us to do something with it
234sub use_reproxy_backend {
235    my $self = $_[0]; # Moobal::Component::Proxy
236    my $be = $_[1]; # Moobal::Component::BackendHTTP
237
238    # get a URI
239    my $datref = $self->{currently_reproxying} = shift @{$self->{reproxy_uris}};
240    unless (defined $datref) {
241        # return error and close the backend
242        $be->close('invalid_uris');
243        return $self->_simple_response(503);
244    }
245
246    # now send request
247    $self->{backend} = $be;
248    $be->{client} = $self;
249
250    my $extra_hdr = "";
251    if (my $range = $self->{req_headers}->header("Range")) {
252        $extra_hdr .= "Range: $range\r\n";
253    }
254    if (my $host = $self->{req_headers}->header("Host")) {
255        $extra_hdr .= "Host: $host\r\n";
256    }
257
258    my $req_method = $self->{req_headers}->request_method eq 'HEAD' ? 'HEAD' : 'GET';
259    my $headers = "$req_method $datref->[2] HTTP/1.0\r\nConnection: keep-alive\r\n${extra_hdr}\r\n";
260
261    $be->{req_headers} = Moobal::HTTPHeaders->new(\$headers);
262    $be->state('sending_req');
263    $self->state('backend_req_sent');
264    $be->write($be->{req_headers}->to_string_ref);
265    $be->watch_read(1);
266    $be->watch_write(1);
267}
268
269# this is called when a transient backend getting a reproxied URI has received
270# a response from the server and is ready for us to deal with it
271sub backend_response_received {
272    my $self = $_[0]; # Moobal::Component::Proxy
273    my $be = $_[1]; # Moobal::Component::BackendHTTP
274
275    # a response means that we are no longer currently waiting on a reproxy, and
276    # don't want to retry this URI
277    $self->{currently_reproxying} = undef;
278
279    # we fail if we got something that's NOT a 2xx code, OR, if we expected
280    # a certain size and got back something different
281    my $code = $be->{res_headers}->response_code + 0;
282
283    my $bad_code = sub {
284        return 0 if $code >= 200 && $code <= 299;
285        return 0 if $code == 416;
286        return 1;
287    };
288
289    my $bad_size = sub {
290        return 0 unless defined $self->{reproxy_expected_size};
291        return $self->{reproxy_expected_size} != $be->{res_headers}->header('Content-length');
292    };
293
294    if ($bad_code->() || $bad_size->()) {
295        # fall back to an alternate URL
296        $be->{client} = undef;
297        $be->close('non_200_reproxy');
298        $self->try_next_uri;
299        return 1;
300    }
301    return 0;
302}
303
304sub start_reproxy_file {
305    my $self = shift; # Moobal::Component::Proxy
306    my $file = shift; # filename to reproxy
307    my $hd = shift; # Moobal::HTTPHeaders headers from backend, in need of cleanup
308    # at this point we need to disconnect from our backend
309    $self->{backend} = undef;
310
311    # call hook for pre-reproxy
312    return if $self->{service}->run_hook("start_file_reproxy", $self, \$file);
313
314    # set our expected size
315    if (my $expected_size = $hd->header('X-REPROXY-EXPECTED-SIZE')) {
316        $self->{reproxy_expected_size} = $expected_size;
317    }
318
319    # start an async stat on the file
320    $self->state('wait_stat');
321    Moobal::AIO::aio_stat($file, sub {
322
323        # if the client's since disconnected by the time we get the stat,
324        # just bail.
325        return if $self->{closed};
326
327        my $size = -s _;
328
329        unless ($size) {
330            # FIXME: POLICY: 404 or retry request to backend w/o reproxy-file capability?
331            return $self->_simple_response(404);
332        }
333        if (defined $self->{reproxy_expected_size} && $self->{reproxy_expected_size} != $size) {
334            # 404; the file size doesn't match what we expected
335            return $self->_simple_response(404);
336        }
337
338        # if the thing we're reproxying is indeed a file, advertise that
339        # we support byteranges on it
340        if (-f _) {
341            $hd->header("Accept-Ranges", "bytes");
342        }
343
344        my ($status, $range_start, $range_end) = $self->{req_headers}->range($size);
345        my $not_satisfiable = 0;
346
347        if ($status == 416) {
348            $hd = Moobal::HTTPHeaders->new_response(416);
349            $hd->header("Content-Range", $size ? "bytes */$size" : "*");
350            $not_satisfiable = 1;
351        }
352
353        # change the status code to 200 if the backend gave us 204 No Content
354        $hd->code(200) if $hd->response_code == 204;
355
356        # fixup the Content-Length header with the correct size (application
357        # doesn't need to provide a correct value if it doesn't want to stat())
358        if ($status == 200) {
359            $hd->header("Content-Length", $size);
360        } elsif ($status == 206) {
361            $hd->header("Content-Range", "bytes $range_start-$range_end/$size");
362            $hd->header("Content-Length", $range_end - $range_start + 1);
363            $hd->code(206);
364        }
365
366        # don't send this internal header to the client:
367        $hd->header('X-REPROXY-FILE', undef);
368
369        # rewrite some other parts of the header
370        $self->setup_keepalive($hd);
371
372        # just send the header, now that we cleaned it.
373        $self->{res_headers} = $hd;
374        $self->write($hd->to_string_ref);
375
376        if ($self->{req_headers}->request_method eq 'HEAD' || $not_satisfiable) {
377            $self->write(sub { $self->http_response_sent; });
378            return;
379        }
380
381        $self->state('wait_open');
382        Moobal::AIO::aio_open($file, 0, 0 , sub {
383            my $fh = shift;
384
385            # if client's gone, just close filehandle and abort
386            if ($self->{closed}) {
387                CORE::close($fh) if $fh;
388                return;
389            }
390
391            # handle errors
392            if (! $fh) {
393                # FIXME: do 500 vs. 404 vs whatever based on $! ?
394                return $self->_simple_response(500);
395            }
396
397            # seek if partial content
398            if ($status == 206) {
399                sysseek($fh, $range_start, &POSIX::SEEK_SET);
400                $size = $range_end - $range_start + 1;
401            }
402
403            $self->reproxy_fh($fh, $size);
404            $self->watch_write(1);
405        });
406    });
407}
408
409# Client
410# get/set backend proxy connection
411sub backend {
412    my $self = shift; # Moobal::Component::Proxy
413    return $self->{backend} unless @_;
414
415    my $backend = shift;
416    $self->state('draining_res') unless $backend;
417    return $self->{backend} = $backend;
418}
419
420# invoked by backend when it wants us to start watching for reads again
421# and feeding it data (if we have any)
422sub backend_ready {
423    my Moobal::Component::Proxy $self = $_[0];
424    my Moobal::Component::BackendHTTP $be = $_[1];
425
426    # if we'd turned ourselves off while we waited for a backend, turn
427    # ourselves back on, because the backend is ready for data now.
428    if ($self->{unread_data_waiting}) {
429        $self->watch_read(1);
430    }
431
432    # normal, not-buffered-to-disk case:
433    return $self->drain_read_buf_to($be) unless $self->{bureason};
434
435    # buffered-to-disk case.
436
437    # tell the backend it has to go into buffered_upload_mode,
438    # which makes it inform us of its writable availability
439    $be->invoke_buffered_upload_mode;
440}
441
442# our backend enqueues a call to this method in our write buffer, so this is called
443# right after we've finished sending all of the results to the user.  at this point,
444# if we were doing keep-alive, we don't close and setup for the next request.
445sub backend_finished {
446    my $self = shift; # Moobal::Component::Proxy
447    print "ClientProxy::backend_finished\n" if &Moobal::DEBUG >= 3;
448
449    # mark ourselves as having responded (presumeably if we're here,
450    # the backend has responded already)
451    $self->{responded} = 1;
452
453    # our backend is done with us, so we disconnect ourselves from it
454    $self->{backend} = undef;
455
456    # backend is done sending data to us, so we can recycle this clientproxy
457    # if we don't have any data yet to read
458    return $self->http_response_sent unless $self->{unread_data_waiting};
459
460    # if we get here (and we do, rarely, in practice) then that means
461    # the backend read was empty/disconected (or otherwise messed up),
462    # and the only thing we can really do is close the client down.
463    $self->close("backend_finished_while_unread_data");
464}
465
466# called when we've sent a response to a user fully and we need to reset state
467sub http_response_sent {
468    my Moobal::Component::Proxy $self = $_[0];
469
470    # persistence logic is in ClientHTTPBase
471    return 0 unless $self->SUPER::http_response_sent;
472
473    print "ClientProxy::http_response_sent -- resetting state\n" if &Moobal::DEBUG >= 3;
474
475    if (my $be = $self->{backend}) {
476        $self->{backend} = undef;
477        $be->forget_client;
478    }
479
480    # if we get here we're being persistent, reset our state
481    $self->{backend_requested} = 0;
482    $self->{high_priority} = 0;
483    $self->{reproxy_uris} = undef;
484    $self->{reproxy_expected_size} = undef;
485    $self->{currently_reproxying} = undef;
486    $self->{content_length_remain} = undef;
487    $self->{primary_res_hdrs} = undef;
488    $self->{responded} = 0;
489    $self->{is_buffering} = 0;
490    $self->{is_writing} = 0;
491    $self->{start_time} = undef;
492    $self->{bufh} = undef;
493    $self->{bufilename} = undef;
494    $self->{buoutpos} = 0;
495    $self->{bureason} = undef;
496    $self->{upload_session} = undef;
497    $self->{chunked_upload_state} = undef;
498    $self->{request_body_length} = undef;
499    return 1;
500}
501
502# to request a backend connection AFTER you've already done so, if you
503# didn't like the results from the first one.  (like after a 500 error)
504sub rerequest_backend {
505    my $self = shift; # Moobal::Component::Proxy
506
507    $self->{backend_requested} = 0;
508    $self->{backend} = undef;
509    $self->request_backend;
510}
511
512sub request_backend {
513    my $self = shift; # Moobal::Component::Proxy
514    return if $self->{backend_requested};
515    $self->{backend_requested} = 1;
516
517    $self->state('wait_backend');
518    $self->request_backend_connection();
519    $self->tcp_cork(1);  # cork writes to self
520}
521
522sub request_backend_connection {
523    my $self = shift;
524
525    return if $self->closed;
526
527    my $hi_pri = $self->{high_priority};  # load values from the client proxy object
528    my $low_pri = $self->{low_priority};  # they are initialized as 0 during object creation, but hooks can override them
529
530    # is there a defined high-priority cookie?
531    my $service = $self->service;
532    if (my $cname = $service->param('high_priority_cookie')) {
533        # decide what priority class this request is in
534        my $hd = $self->{req_headers};
535        my %cookie;
536        foreach (split(/;\s+/, $hd->header("Cookie") || '')) {
537            next unless ($_ =~ /(.*)=(.*)/);
538            $cookie{Moobal::Util::durl($1)} = Moobal::Util::durl($2);
539        }
540        my $hicookie = $cookie{$cname} || "";
541        $hi_pri = index($hicookie, $service->param('high_priority_cookie_contents')) != -1;
542    }
543
544    # now, call hook to see if this should be high priority
545    $hi_pri = $service->run_hook('make_high_priority', $self)
546        unless $hi_pri; # only if it's not already
547
548    # and then, call hook to see about low priority
549    $low_pri = $service->run_hook('make_low_priority', $self)
550        unless $hi_pri || $low_pri; # only if it's not high or low already
551
552    $self->{high_priority} = 1 if $hi_pri;
553    $self->{low_priority} = 1 if $low_pri;
554
555    # before we even consider spawning backends, let's see if we have
556    # some bored (pre-connected) backends that'd take this client
557    my $be;
558    my $now = time;
559    while ($be = shift @{$self->{bored_backends}}) {
560        next if $be->{closed};
561
562        # now make sure that it's still in our pool, and if not, close it
563        next unless $self->verify_generation($be);
564
565        # don't use connect-ahead connections when we haven't
566        # verified we have their attention
567        if (! $be->{has_attention} && $be->{create_time} < $now - 5) {
568            $be->close("too_old_bored");
569            next;
570        }
571
572        # don't use keep-alive connections if we know the server's
573        # just about to kill the connection for being idle
574        if ($be->{disconnect_at} && $now + 2 > $be->{disconnect_at}) {
575            $be->close("too_close_disconnect");
576            next;
577        }
578
579        # give the backend this client
580        if ($be->assign_client($self)) {
581            # and make some extra bored backends, if configured as such
582            $self->spawn_backends;
583            return;
584        }
585
586        # assign client can end up closing the connection, so check for that
587        return if $self->{closed};
588    }
589
590    if ($hi_pri) {
591        push @{$self->{waiting_clients_highpri}}, $self;
592    } elsif ($low_pri) {
593        push @{$self->{waiting_clients_lowpri}}, $self;
594    } else {
595        push @{$self->{waiting_clients}}, $self;
596    }
597
598    $self->{waiting_client_count}++;
599    $self->{waiting_client_map}{$self->socket->fileno} = 1;
600
601    $self->spawn_backends;
602}
603
604# sees if it should spawn one or more backend connections
605sub spawn_backends {
606    my $self = shift;
607
608    # check our lock and set it if we can
609    return if $self->spawn_lock;
610    $self->spawn_lock( 1 );
611
612    # sanity checks on our bookkeeping
613    if ($self->pending_connect_count < 0) {
614        Moobal::log('crit', "Bogus: service @{[$self->service->name]} has pending connect ".
615                     "count of @{[$self->{pending_connect_count}]}?!  Resetting.");
616        $self->pending_connect_count(
617            scalar
618                map { $_ && ! $_->closed } values %{$self->pending_connects}
619        );
620    }
621
622    # keep track of the sum of existing_bored + bored_created
623    my $backends_created = scalar(@{$self->bored_backends}) + $self->pending_connect_count;
624    my $backends_needed = $self->waiting_client_count + $self->connect_ahead;
625    my $to_create = $backends_needed - $backends_created;
626
627    my $pool = $self->{pool};
628
629    # can't create more than this, assuming one pending connect per node
630    my $max_creatable = $pool ? ($self->{pool}->node_count - $self->{pending_connect_count}) : 1;
631    $to_create = $max_creatable if $to_create > $max_creatable;
632
633    # cap number of attempted connects at once
634    $to_create = 10 if $to_create > 10;
635
636    my $now = time;
637
638    while ($to_create > 0) {
639        $to_create--;
640
641        # spawn processes if not a pool, else whine.
642        unless ($pool) {
643            if (my $sp = $self->{server_process}) {
644                warn "To create = $to_create...\n";
645                warn "  spawing $sp\n";
646                my $be = Moobal::Component::BackendHTTP->new_process($self, $sp);
647                return;
648            }
649            warn "No pool! Can't spawn backends.\n";
650            return;
651        }
652
653        my ($ip, $port) = $self->{pool}->get_backend_endpoint;
654        unless ($ip) {
655            Moobal::log('crit', "No backend IP for service $self->{name}");
656            # FIXME: register desperate flag, so load-balancer module can callback when it has a node
657            $self->spawn_lock( 0 );
658            return;
659        }
660
661        # handle retry timeouts so we don't spin
662        next if $self->{backend_no_spawn}->{"$ip:$port"};
663
664        # if it's pending, verify the pending one is still valid
665        if (my $be = $self->{pending_connects}{"$ip:$port"}) {
666            my $age = $now - $be->{create_time};
667            if ($age >= 5 && $be->{state} eq "connecting") {
668                $be->close('connect_timeout');
669            } elsif ($age >= 60 && $be->{state} eq "verifying_backend") {
670                # after 60 seconds of attempting to verify, we're probably already dead
671                $be->close('verify_timeout');
672            } elsif (! $be->{closed}) {
673                next;
674            }
675        }
676
677        # now actually spawn a backend and add it to our pending list
678        if (my $be = Moobal::Component::BackendHTTP->new($self, $ip, $port, { pool => $self->{pool} })) {
679            $self->add_pending_connect($be);
680        }
681    }
682
683    # clear our spawn lock
684    $self->spawn_lock( 0 );
685}
686
687
688
689
690# Client (overrides and calls super)
691sub close {
692    my $self = shift; # Moobal::Component::Proxy
693    my $reason = shift;
694
695    warn sprintf(
696                    "Moobal::Component::Proxy closed %s%s.\n",
697                    ( $self->{closed} ? "again " : "" ),
698                    (defined $reason ? "saying '$reason'" : "for an unknown reason")
699    ) if &Moobal::DEBUG >= 2;
700
701    # don't close twice
702    return if $self->{closed};
703
704    # signal that we're done
705    $self->{service}->run_hooks('end_proxy_request', $self);
706
707    # kill our backend if we still have one
708    if (my $backend = $self->{backend}) {
709        print "Client ($self) closing backend ($backend)\n" if &Moobal::DEBUG >= 1;
710        $self->backend(undef);
711        $backend->close($reason ? "proxied_from_client_close:$reason" : "proxied_from_client_close");
712    } else {
713        # if no backend, tell our service that we don't care for one anymore
714        $self->{service}->note_client_close($self);
715    }
716
717    # call ClientHTTPBase's close
718    $self->SUPER::close($reason);
719}
720
721sub client_disconnected { # : void
722    my $self = shift; # Moobal::Component::Proxy
723    print "ClientProxy::client_disconnected\n" if &Moobal::DEBUG >= 2;
724
725    # if client disconnected, then we need to turn off watching for
726    # further reads and purge the existing upload if any. also, we
727    # should just return and do nothing else.
728
729    $self->watch_read(0);
730    $self->purge_buffered_upload if $self->{bureason};
731    return $self->close('user_disconnected');
732}
733
734# Client
735sub event_write {
736    my $self = shift; # Moobal::Component::Proxy
737    print "ClientProxy::event_write\n" if &Moobal::DEBUG >= 3;
738
739    $self->SUPER::event_write;
740
741    # obviously if we're writing the backend has processed our request
742    # and we are responding/have responded to the user, so mark it so
743    $self->{responded} = 1;
744
745    # trigger our backend to keep reading, if it's still connected
746    if ($self->{backend_stalled} && (my $backend = $self->{backend})) {
747        print "  unstalling backend\n" if &Moobal::DEBUG >= 3;
748
749        $self->{backend_stalled} = 0;
750        $backend->watch_read(1);
751    }
752}
753
754# ClientProxy
755sub event_read {
756    my $self = shift; # Moobal::Component::Proxy
757    print "ClientProxy::event_read\n" if &Moobal::DEBUG >= 3;
758
759    # mark alive so we don't get killed for being idle
760    $self->{alive_time} = time;
761
762    # if we have no headers, the only thing we can do is try to get some
763    if (! $self->{req_headers}) {
764        print "  no headers.  reading.\n" if &Moobal::DEBUG >= 3;
765        $self->handle_request if $self->read_request_headers;
766        return;
767    }
768
769    # if we're buffering to disk or haven't read too much from this client, keep reading,
770    # otherwise shut off read notifications
771    unless ($self->{is_buffering} || $self->{read_ahead} < READ_AHEAD_SIZE) {
772        # our buffer is full, so turn off reads for now
773        print "  disabling reads.\n" if &Moobal::DEBUG >= 3;
774        $self->watch_read(0);
775        return;
776    }
777
778    # deal with chunked uploads
779    if (my $cus = $self->{chunked_upload_state}) {
780        $cus->on_readable($self);
781
782        # if we got more than 1MB not flushed to disk,
783        # stop reading for a bit until disk catches up
784        if ($self->{read_ahead} > 1024*1024) {
785            $self->watch_read(0);
786        }
787        return;
788    }
789
790    # read more data if we're still buffering or if our current read buffer
791    # is not full to the max READ_AHEAD_SIZE which is how much data we will
792    # buffer in from the user before passing on to the backend
793
794    # read the MIN(READ_SIZE, content_length_remain)
795    my $read_size = READ_SIZE;
796    my $remain = $self->{content_length_remain};
797
798    $read_size = $remain if $remain && $remain < $read_size;
799    print "  reading $read_size bytes (", (defined $remain ? $remain : "(undef)"), " bytes remain)\n" if &Moobal::DEBUG >= 3;
800
801    my $bref = $self->read($read_size);
802
803    # if the read returned undef, that means the connection was closed
804    # (see: Danga::Socket::read)
805    return $self->client_disconnected unless defined $bref;
806
807    # if they didn't declare a content body length and we just got a
808    # readable event that's not a disconnect, something's messed up.
809    # they're overflowing us.  disconnect!
810    if (! $remain) {
811        $self->_simple_response(400, "Can't pipeline to HTTP/1.0");
812        $self->close("pipelining_to_http10");
813        return;
814    }
815
816    # now that we know we have a defined value, determine how long it is, and do
817    # housekeeping to keep our tracking numbers up to date.
818    my $len = length($$bref);
819    print "  read $len bytes\n" if &Moobal::DEBUG >= 3;
820
821    # when run under the program "trickle", epoll speaks the truth to
822    # us, but then trickle interferes and steals our reads/writes, so
823    # this fails.  normally this check isn't needed.
824    return unless $len;
825
826    $self->{read_size} += $len;
827    $self->{content_length_remain} -= $len if $remain;
828
829    my $done_reading = defined $self->{content_length_remain} && $self->{content_length_remain} <= 0;
830    my $backend = $self->backend;
831    print("  done_reading = $done_reading, backend = ", ($backend || "<undef>"), "\n") if &Moobal::DEBUG >= 3;
832
833    # upload tracking
834    if (my $session = $self->{upload_session}) {
835        my $cl = $self->{req_headers}->content_length;
836        my $remain = $self->{content_length_remain};
837        my $now = time();  # FIXME: more efficient?
838        if ($cl && $remain && ($self->{last_upload_packet} || 0) != $now) {
839            my $done = $cl - $remain;
840            $self->{last_upload_packet} = $now;
841            $udp_sock ||= IO::Socket::INET->new(Proto => 'udp');
842            my $since = $self->{last_request_time};
843            my $send = "UPLOAD:$session:$done:$cl:$since:$now";
844            if ($udp_sock) {
845                foreach my $ep (@{ $self->{service}{upload_status_listeners_sockaddr} }) {
846                    my $rv = $udp_sock->send($send, 0, $ep);
847                }
848            }
849        }
850    }
851
852    # just dump the read into the nether if we're dangling. that is
853    # the case when we send the headers to the backend and it responds
854    # before we're done reading from the client; therefore further
855    # reads from the client just need to be sent nowhere, because the
856    # RFC2616 section 8.2.3 says: "the server SHOULD NOT close the
857    # transport connection until it has read the entire request"
858    if ($self->{responded}) {
859        print "  already responded.\n" if &Moobal::DEBUG >= 3;
860        # in addition, if we're now out of data (clr == 0), then we should
861        # either close ourselves or get ready for another request
862        return $self->http_response_sent if $done_reading;
863
864        print "  already responded [2].\n" if &Moobal::DEBUG >= 3;
865        # at this point, if the backend has responded then we just return
866        # as we don't want to send it on to them or buffer it up, which is
867        # what the code below does
868        return;
869    }
870
871    # if we have no data left to read, stop reading.  all that can
872    # come later is an extra \r\n which we handle later when parsing
873    # new request headers.  and if it's something else, we'll bail on
874    # the next request, not this one.
875    if ($done_reading) {
876        Carp::confess("content_length_remain less than zero: self->{content_length_remain}")
877            if $self->{content_length_remain} < 0;
878        $self->{unread_data_waiting} = 0;
879        $self->watch_read(0);
880    }
881
882    # now, if we have a backend, then we should be writing it to the backend
883    # and not doing anything else
884    if ($backend) {
885        print "  got a backend.  sending write to it.\n" if &Moobal::DEBUG >= 3;
886        $backend->write($bref);
887        # TODO: monitor the backend's write buffer depth?
888        return;
889    }
890
891    # now, we know we don't have a backend, so we have to push this data onto our
892    # read buffer... it's not going anywhere yet
893    push @{$self->{read_buf}}, $bref;
894    $self->{read_ahead} += $len;
895    print "  no backend.  read_ahead = $self->{read_ahead}.\n" if &Moobal::DEBUG >= 3;
896
897    # if we know we've already started spooling a file to disk, then continue
898    # to do that.
899    print "  bureason = $self->{bureason}\n" if &Moobal::DEBUG >= 3 && $self->{bureason};
900    return $self->buffered_upload_update if $self->{bureason};
901
902    # if we are under our buffer-to-memory size, just continue buffering here and
903    # don't fall through to the backend request call below
904    return if
905        ! $done_reading &&
906        $self->{read_ahead} < $self->{service}->{buffer_backend_connect};
907
908    # over the buffer-to-memory size, see if we should start spooling to disk.
909    return if $self->{service}->{buffer_uploads} && $self->decide_to_buffer_to_disk;
910
911    # give plugins a chance to act on the request before we request a backend
912    # (added by Chris Hondl <chris@imvu.com>, March 2006)
913    my $svc = $self->{service};
914    return if $svc->run_hook('proxy_read_request', $self);
915
916    # if we fall through to here, we need to ensure that a backend is on the
917    # way, because no specialized handling took over above
918    print "  finally requesting a backend\n" if &Moobal::DEBUG >= 3;
919    return $self->request_backend;
920}
921
922sub handle_request {
923    my $self = shift; # Moobal::Component::Proxy
924    my $req_hd = $self->{req_headers};
925
926    unless ($req_hd) {
927        $self->close("handle_request without headers");
928        return;
929    }
930
931    $self->check_req_headers;
932
933    my $svc = $self->{service};
934    # give plugins a chance to force us to bail
935    return if $svc->run_hook('start_proxy_request', $self);
936    return if $svc->run_hook('start_http_request',  $self);
937
938    if ($self->handle_chunked_upload) {
939        # handled in method.
940    } else {
941        # if defined we're waiting on some amount of data.  also, we have to
942        # subtract out read_size, which is the amount of data that was
943        # extra in the packet with the header that's part of the body.
944        $self->{request_body_length} =
945            $self->{content_length_remain} =
946            $req_hd->content_length;
947        $self->{unread_data_waiting} = 1 if $self->{content_length_remain};
948    }
949
950    # upload-tracking stuff.  both starting a new upload track session,
951    # and checking on status of ongoing one
952    return if $svc->{upload_status_listeners} && $self->handle_upload_tracking;
953
954    # note that we've gotten a request
955    $self->{requests}++;
956    $self->{last_request_time} = $self->{alive_time};
957
958    # either start buffering some of the request to memory, or
959    # immediately request a backend connection.
960    if ($self->{chunked_upload_state}) {
961        $self->{request_body_length} = 0;
962        $self->{is_buffering} = 1;
963        $self->{bureason} = 'chunked';
964        $self->buffered_upload_update;
965    } elsif ($self->{content_length_remain} && $self->{service}->{buffer_backend_connect}) {
966        # the deeper path
967        $self->start_buffering_request;
968    } else {
969        # get the backend request process moving, since we aren't buffering
970        $self->{is_buffering} = 0;
971
972        # if reproxy-caching is enabled, we can often bypass needing to allocate a BackendHTTP connection:
973        return if $svc->{reproxy_cache} && $self->satisfy_request_from_cache;
974
975        $self->request_backend;
976    }
977}
978
979sub handle_chunked_upload {
980    my $self = shift; # Moobal::Component::Proxy
981    my $req_hd = $self->{req_headers};
982    my $te = $req_hd->header("Transfer-Encoding");
983    return unless $te && $te eq "chunked";
984    return unless $self->{service}->{buffer_uploads};
985
986    $req_hd->header("Transfer-Encoding", undef); # remove it (won't go to backend)
987
988    my $eh = $req_hd->header("Expect");
989    if ($eh && $eh =~ /\b100-continue\b/) {
990        $self->write(\ "HTTP/1.1 100 Continue\r\n\r\n");
991        $req_hd->header("Expect", undef); # remove it (won't go to backend)
992    }
993
994    my $max_size = $self->{service}{max_chunked_request_size};
995
996    my $args = {
997        on_new_chunk => sub {
998            my $cref = shift;
999            my $len = length($$cref);
1000            push @{$self->{read_buf}}, $cref;
1001            $self->{read_ahead}          += $len;
1002            $self->{request_body_length} += $len;
1003
1004            # if too large, disconnect them...
1005            if ($max_size && $self->{request_body_length} > $max_size) {
1006                $self->purge_buffered_upload;
1007                $self->close;
1008                return;
1009            }
1010            $self->buffered_upload_update;
1011        },
1012        on_disconnect => sub {
1013            $self->client_disconnected;
1014        },
1015        on_zero_chunk => sub {
1016            $self->send_buffered_upload;
1017        },
1018    };
1019
1020    $self->{chunked_upload_state} = Moobal::ChunkedUploadState->new(%$args);
1021    return 1;
1022}
1023
1024sub satisfy_request_from_cache {
1025    my $self = shift; # Moobal::Component::Proxy
1026
1027    my $req_hd = $self->{req_headers};
1028    my $svc    = $self->{service};
1029    my $cache  = $svc->{reproxy_cache};
1030    $svc->{_stat_requests}++;
1031
1032    my $requri   = $req_hd->request_uri    || '';
1033    my $hostname = $req_hd->header("Host") || '';
1034
1035    my $key      = "$hostname|$requri";
1036
1037    my $reproxy  = $cache->get($key) or
1038        return 0;
1039
1040    my ($timeout, $headers, $urls) = @$reproxy;
1041    return 0 if time() > $timeout;
1042
1043    $svc->{_stat_cache_hits}++;
1044    my %headers = map { ref $_ eq 'SCALAR' ? $$_ : $_ } @{$headers || []};
1045
1046    if (my $ims = $req_hd->header("If-Modified-Since")) {
1047        my ($lm_key) = grep { uc($_) eq "LAST-MODIFIED" } keys %headers;
1048        my $lm = $headers{$lm_key} || "";
1049
1050        # remove the IE length suffix
1051        $ims =~ s/; length=(\d+)//;
1052
1053        # If 'Last-Modified' is same as 'If-Modified-Since', send a 304
1054        if ($ims eq $lm) {
1055            my $res_hd = Moobal::HTTPHeaders->new_response(304);
1056            $res_hd->header("Content-Length", "0");
1057            $self->tcp_cork(1);
1058            $self->state('xfer_resp');
1059            $self->write($res_hd->to_string_ref);
1060            $self->write(sub { $self->http_response_sent; });
1061            return 1;
1062        }
1063    }
1064
1065    my $res_hd = Moobal::HTTPHeaders->new_response(200);
1066    $res_hd->header("Date", HTTP::Date::time2str(time()));
1067    while (my ($key, $value) = each %headers) {
1068        $res_hd->header($key, $value);
1069    }
1070
1071    $self->start_reproxy_uri($res_hd, $urls);
1072    return 1;
1073}
1074
1075# return 1 to steal this connection (when they're asking status of an
1076# upload session), return 0 to return it to handle_request's control.
1077sub handle_upload_tracking {
1078    my $self = shift; # Moobal::Component::Proxy
1079    my $req_hd = $self->{req_headers};
1080
1081    return 0 unless
1082        $req_hd->request_uri =~ /[\?&]client_up_sess=(\w{5,50})\b/;
1083
1084    my $sess = $1;
1085
1086    # getting status?
1087    if ($req_hd->request_uri =~ m!^/__upload_status\?!) {
1088        my $status = Moobal::UploadListener::get_status($sess);
1089        my $now = time();
1090        my $body = $status ?
1091            "{done:$status->{done},total:$status->{total},starttime:$status->{starttime},nowtime:$now}" :
1092            "{}";
1093
1094        my $res = $self->{res_headers} = Moobal::HTTPHeaders->new_response(200);
1095        $res->header("Content-Type", "text/plain");
1096        $res->header('Content-Length', length $body);
1097        $self->setup_keepalive($res);
1098        $self->tcp_cork(1);  # cork writes to self
1099        $self->write($res->to_string_ref);
1100        $self->write(\ $body);
1101        $self->write(sub { $self->http_response_sent; });
1102        return 1;
1103    }
1104
1105    # otherwise just tagging this upload as a new upload session
1106    $self->{upload_session} = $sess;
1107    return 0;
1108}
1109
1110# continuation of handle_request, in the case where we need to start buffering
1111# a bit of the request body to memory, either hoping that's all of it, or to
1112# make a determination of whether or not we should save it all to disk first
1113sub start_buffering_request {
1114    my $self = shift; # Moobal::Component::Proxy
1115
1116    # buffering case:
1117    $self->{is_buffering} = 1;
1118
1119    # shortcut: if we know that we're buffering by size, and the size
1120    # of this upload is bigger than that value, we can just turn on spool
1121    # to disk right now...
1122    if ($self->{service}->{buffer_uploads} && $self->{service}->{buffer_upload_threshold_size}) {
1123        my $req_hd = $self->{req_headers};
1124        if ($req_hd->content_length >= $self->{service}->{buffer_upload_threshold_size}) {
1125            $self->{bureason} = 'size';
1126            if ($ENV{PERLBAL_DEBUG_BUFFERED_UPLOADS}) {
1127                $self->{req_headers}->header('X-PERLBAL-BUFFERED-UPLOAD-REASON', 'size');
1128            }
1129            $self->state('buffering_upload');
1130            $self->buffered_upload_update;
1131            return;
1132        }
1133    }
1134
1135    # well, we're buffering, but we're not going to disk just yet (but still might)
1136    $self->state('buffering_request');
1137
1138    # only need time if we are using the buffer to disk functionality
1139    $self->{start_time} = [ gettimeofday() ]
1140        if $self->{service}->{buffer_uploads};
1141}
1142
1143# looks at our states and decides if we should start writing to disk
1144# or should just go ahead and blast this to the backend.  returns 1
1145# if the decision was made to buffer to disk
1146sub decide_to_buffer_to_disk {
1147    my $self = shift; # Moobal::Component::Proxy
1148    return unless $self->{is_buffering};
1149    return $self->{bureason} if defined $self->{bureason};
1150
1151    # this is called when we have enough data to determine whether or not to
1152    # start buffering to disk
1153    my $dur = tv_interval($self->{start_time}) || 1;
1154    my $rate = $self->{read_ahead} / $dur;
1155    my $etime = $self->{content_length_remain} / $rate;
1156
1157    # see if we have enough data to make the determination
1158    my $reason = undef;
1159
1160    # see if we blow the rate away
1161    if ($self->{service}->{buffer_upload_threshold_rate} > 0 &&
1162            $rate < $self->{service}->{buffer_upload_threshold_rate}) {
1163        # they are slower than the minimum rate
1164        $reason = 'rate';
1165    }
1166
1167    # and finally check estimated time exceeding
1168    if ($self->{service}->{buffer_upload_threshold_time} > 0 &&
1169            $etime > $self->{service}->{buffer_upload_threshold_time}) {
1170        # exceeds
1171        $reason = 'time';
1172    }
1173
1174    unless ($reason) {
1175        $self->{is_buffering} = 0;
1176        return 0;
1177    }
1178
1179    # start saving it to disk
1180    $self->state('buffering_upload');
1181    $self->buffered_upload_update;
1182    $self->{bureason} = $reason;
1183
1184    if ($ENV{PERLBAL_DEBUG_BUFFERED_UPLOADS}) {
1185        $self->{req_headers}->header('X-PERLBAL-BUFFERED-UPLOAD-REASON', $reason);
1186    }
1187
1188    return 1;
1189}
1190
1191# take ourselves and send along our buffered data to the backend
1192sub send_buffered_upload {
1193    my $self = shift; # Moobal::Component::Proxy
1194
1195    # make sure our buoutpos is the same as the content length...
1196    return if $self->{is_writing};
1197
1198    # set the content-length that goes to the backend...
1199    if ($self->{chunked_upload_state}) {
1200        $self->{req_headers}->header("Content-Length", $self->{request_body_length});
1201    }
1202
1203    my $clen = $self->{req_headers}->content_length;
1204    if ($clen != $self->{buoutpos}) {
1205        Moobal::log('critical', "Content length of $clen declared but $self->{buoutpos} bytes written to disk");
1206        return $self->_simple_response(500);
1207    }
1208
1209    # reset our position so we start reading from the right spot
1210    $self->{buoutpos} = 0;
1211    sysseek($self->{bufh}, 0, 0) if ($self->{bufh}); # But only if it exists at all
1212
1213    # notify that we want the backend so we get the ball rolling
1214    $self->request_backend;
1215}
1216
1217sub continue_buffered_upload {
1218    my $self = shift; # Moobal::Component::Proxy
1219    my $be = shift; # Moobal::Component::BackendHTTP
1220    return unless $self && $be;
1221
1222    # now send the data
1223    my $clen = $self->{request_body_length};
1224
1225    if ($self->{buoutpos} < $clen) {
1226        my $sent = Moobal::Socket::sendfile($be->{fd}, fileno($self->{bufh}), $clen - $self->{buoutpos});
1227        if ($sent < 0) {
1228            return $self->close("epipe") if $! == EPIPE;
1229            return $self->close("connreset") if $! == ECONNRESET;
1230            print STDERR "Error w/ sendfile: $!\n";
1231            return $self->close('sendfile_error');
1232        }
1233        $self->{buoutpos} += $sent;
1234    }
1235
1236    # if we're done, purge the file and move on
1237    if ($self->{buoutpos} >= $clen) {
1238        $be->{buffered_upload_mode} = 0;
1239        $self->purge_buffered_upload;
1240        return;
1241    }
1242
1243    # we will be called again by the backend since buffered_upload_mode is on
1244}
1245
1246# write data to disk
1247sub buffered_upload_update {
1248    my $self = shift; #  Moobal::Component::Proxy
1249    return if $self->{is_writing};
1250    return unless $self->{is_buffering} && $self->{read_ahead};
1251
1252    # so we're not writing now and we have data to write...
1253    unless ($self->{bufilename}) {
1254        # create a filename and see if it exists or not
1255        $self->{is_writing} = 1;
1256        my $fn = join('-', $self->{service}->name, $self->{service}->listenaddr, "client", $self->{fd}, int(rand(0xffffffff)));
1257        $fn = $self->{service}->{buffer_uploads_path} . '/' . $fn;
1258
1259        # good, now we need to create the file
1260        Moobal::AIO::aio_open($fn, O_CREAT | O_TRUNC | O_RDWR, 0644, sub {
1261            $self->{is_writing} = 0;
1262            $self->{bufh} = shift;
1263
1264            # throw errors back to the user
1265            if (! $self->{bufh}) {
1266                Moobal::log('critical', "Failure to open $fn for buffered upload output");
1267                return $self->_simple_response(500);
1268            }
1269
1270            # save state and info and bounce it back to write data
1271            $self->{bufilename} = $fn;
1272            $self->buffered_upload_update;
1273        });
1274
1275        return;
1276    }
1277
1278    # can't proceed if we have no disk file to async write to
1279    # people reported seeing this crash rarely in production...
1280    # must be a race between previously in-flight's write
1281    # re-invoking a write immediately after something triggered
1282    # a buffered upload purge.
1283    unless ($self->{bufh}) {
1284        $self->close;
1285        return;
1286    }
1287
1288    # at this point, we want to do some writing
1289    my $bref = shift(@{$self->{read_buf}});
1290    my $len = length $$bref;
1291    $self->{read_ahead} -= $len;
1292
1293    # so at this point we have a valid filename and file handle and should write out
1294    # the buffer that we have
1295    $self->{is_writing} = 1;
1296    Moobal::AIO::aio_write($self->{bufh}, $self->{buoutpos}, $len, $$bref, sub {
1297        my $bytes = shift;
1298        $self->{is_writing} = 0;
1299
1300        # check for error
1301        unless ($bytes) {
1302            Moobal::log('critical', "Error writing buffered upload: $!.  Tried to do $len bytes at $self->{buoutpos}.");
1303            return $self->_simple_response(500);
1304        }
1305
1306        # update our count of data written
1307        $self->{buoutpos} += $bytes;
1308
1309        # now check if we wrote less than we had in this chunk of buffer.  if that's
1310        # the case then we need to reenqueue the part of the chunk that wasn't
1311        # written out and update as appropriate.
1312        if ($bytes < $len) {
1313            my $diff = $len - $bytes;
1314            unshift @{$self->{read_buf}}, \ substr($$bref, $bytes, $diff);
1315            $self->{read_ahead} += $diff;
1316        }
1317
1318        # if we're processing a chunked upload, ...
1319        if ($self->{chunked_upload_state}) {
1320            # turn reads back on, if we haven't hit the end yet.
1321            if ($self->{unread_data_waiting} && $self->{read_ahead} < 1024*1024) {
1322                $self->watch_read(1);
1323                $self->{unread_data_waiting} = 0;
1324            }
1325
1326            if ($self->{read_ahead} == 0 && $self->{chunked_upload_state}->hit_zero_chunk) {
1327                $self->watch_read(0);
1328                $self->send_buffered_upload;
1329                return;
1330            }
1331        }
1332
1333        # if we're done (no clr and no read ahead!) then send it
1334        elsif ($self->{read_ahead} <= 0 && $self->{content_length_remain} <= 0) {
1335            $self->send_buffered_upload;
1336            return;
1337        }
1338
1339        # spawn another writer!
1340        $self->buffered_upload_update;
1341    });
1342}
1343
1344# destroy any files we've created
1345sub purge_buffered_upload {
1346    my $self = shift; # Moobal::Component::Proxy
1347
1348    # Main reason for failure below is a 0-length chunked upload, where the file is never created.
1349    return unless $self->{bufh};
1350
1351    # FIXME: it's reported that sometimes the two now-in-eval blocks
1352    # fail, hence the eval blocks and warnings.  the FIXME is to
1353    # figure this out, why it happens sometimes.
1354
1355    # first close our filehandle... not async
1356    eval {
1357        CORE::close($self->{bufh});
1358    };
1359    if ($@) { warn "Error closing file in ClientProxy::purge_buffered_upload: $@\n"; }
1360
1361    $self->{bufh} = undef;
1362
1363    eval {
1364        # now asyncronously unlink the file
1365        Moobal::AIO::aio_unlink($self->{bufilename}, sub {
1366            if ($!) {
1367                # note an error, but whatever, we'll either overwrite the file later (O_TRUNC | O_CREAT)
1368                # or a cleaner will come through and do it for us someday (if the user runs one)
1369                Moobal::log('warning', "Unable to link $self->{bufilename}: $!");
1370              }
1371        });
1372    };
1373    if ($@) { warn "Error unlinking file in ClientProxy::purge_buffered_upload: $@\n"; }
1374}
1375
1376# returns bool; whether backend should hide the 500 error from the client
1377#   and have us try a new backend.  return true to retry, false to get a 500 error.
1378sub should_retry_after_500 {
1379    my $self = shift; # Moobal::Component::Proxy
1380    my $be   = shift; # Moobal::Component::BackendHTTP
1381    my $svc = $be->{service};
1382    return 0 unless $svc->{enable_error_retries};
1383    my @sched = split(/\s*,\s*/, $svc->{error_retry_schedule});
1384    return 0 if ++$self->{retry_count} > @sched;
1385    return 1;
1386}
1387
1388# called by Backend to tell us it got a 500 error and we should retry another backend.
1389sub retry_after_500 {
1390    my $self = shift; # Moobal::Component::Proxy
1391    my $svc  = shift; # Moobal::Service     
1392
1393    my @sched = split(/\s*,\s*/, $svc->{error_retry_schedule});
1394    my $delay = $sched[$self->{retry_count} - 1];
1395
1396    if ($delay) {
1397        Danga::Socket->AddTimer($delay, sub {
1398            return if $self->{closed};
1399            $self->rerequest_backend;
1400        });
1401    } else {
1402        $self->rerequest_backend;
1403    }
1404
1405}
1406
1407sub as_string {
1408    my $self = shift; # Moobal::Component::Proxy
1409
1410    my $ret = $self->SUPER::as_string;
1411    if ($self->{backend}) {
1412        my $ipport = $self->{backend}->{ipport};
1413        $ret .= "; backend=$ipport";
1414    } else {
1415        $ret .= "; write_buf_size=$self->{write_buf_size}"
1416            if $self->{write_buf_size} > 0;
1417    }
1418    $ret .= "; highpri" if $self->{high_priority};
1419    $ret .= "; lowpri" if $self->{low_priority};
1420    $ret .= "; responded" if $self->{responded};
1421    $ret .= "; waiting_for=" . $self->{content_length_remain}
1422        if defined $self->{content_length_remain};
1423    $ret .= "; reproxying" if $self->{currently_reproxying};
1424
1425    return $ret;
1426}
1427
1428sub set_queue_low {
1429    my $self = shift; # Moobal::Component::Proxy
1430    $self->{low_priority} = 1;
1431    return;
1432}
1433
1434sub set_queue_high {
1435    my $self = shift; # Moobal::Component::Proxy
1436    $self->{high_priority} = 1;
1437    return;
1438}
1439
14401;
1441
1442
1443# Local Variables:
1444# mode: perl
1445# c-basic-indent: 4
1446# indent-tabs-mode: nil
1447# End:
Note: See TracBrowser for help on using the browser.