File Coverage

blib/lib/Perlbal/ClientProxy.pm
Criterion Covered Total %
statement 483 632 76.4
branch 173 290 59.6
condition 68 113 60.1
subroutine 51 62 82.2
pod 5 37 13.5
total 780 1134 68.7


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