forked from bobtfish/MogileFS-Client-Async
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Async.pm
314 lines (264 loc) · 9.43 KB
/
Async.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package MogileFS::Client::Async;
use strict;
use warnings;
use AnyEvent;
use AnyEvent::HTTP;
use AnyEvent::Socket;
use URI;
use Carp qw/confess/;
use POSIX qw( EAGAIN );
use Socket qw/ IPPROTO_TCP /;
use base qw/ MogileFS::Client /;
use IO::AIO qw/ fadvise /;
use constant TCP_CORK => ($^O eq "linux" ? 3 : 0); # XXX
our $VERSION = '0.020';
=head1 NAME
MogileFS:Client::Async
=head1 SYNOPSIS
my $mogfs = MogileFS::Client::Async->new( ... )
$mogfs->read_to_file($key, $filename);
$mogfs->store_file($key, $class, $filename, \%opts );
$mogfs->store_content($key, $class, \$content, \%opts );
=head1 DESCRIPTION
This package provides replacement implementations of some methods in
L<MogileFS::Client> to allow for non-blocking IO under L<AnyEvent> and the
ability to read and write files stored in MogileFS without needing to store
the entire file in memory.
=head1 SEE ALSO
=over
=item *
L<AnyEvent>
=item *
L<MogileFS::Client>
=item *
L<http://danga.com/mogilefs/>
=back
=cut
use namespace::clean;
sub new_file { confess("new_file is unsupported in " . __PACKAGE__) }
sub edit_file { confess("edit_file is unsupported in " . __PACKAGE__) }
sub read_file { confess("read_file is unsupported in " . __PACKAGE__) }
sub read_to_file {
my $self = shift;
my $key = shift;
my $fn = shift;
my @paths = $self->get_paths($key);
die("No paths for $key") unless @paths;
for (1..2) {
foreach my $path (@paths) {
my ($bytes, $write) = (0, undef);
open $write, '>', $fn or confess("Could not open $fn to write");
my $cv = AnyEvent->condvar;
my $h;
my $guard = http_request
GET => $path,
timeout => 120, # 2m
on_header => sub {
my ($headers) = @_;
return 0 if ($headers->{Status} != 200);
$h = $headers;
1;
},
on_body => sub {
syswrite $write, $_[0] or return 0;
$bytes += length($_[0]);
1;
},
sub { # On complete!
my (undef, $headers) = @_;
$h = $headers;
close($write);
undef $write;
$cv->send;
1;
};
$cv->recv;
return $bytes if ($bytes && !$write);
# Error..
$h->{Code} = 590;
$h->{Reason} = "Unknown error";
warn("HTTP error getting mogile $key: " . $h->{Reason} . "\n");
close $write;
unlink $fn;
}
}
confess("Could not read $key from mogile");
}
sub store_file {
my $self = shift;
return undef if $self->{readonly};
my ($key, $class, $file, $opts) = @_;
$opts ||= {};
# Extra args to be passed along with the create_open and create_close commands.
# Any internally generated args of the same name will overwrite supplied ones in
# these hashes.
my $create_open_args = $opts->{create_open_args} || {};
my $create_close_args = $opts->{create_close_args} || {};
$self->run_hook('store_file_start', $self, $key, $class, $opts);
$self->run_hook('new_file_start', $self, $key, $class, $opts);
my $res = $self->{backend}->do_request(
create_open => {
%$create_open_args,
domain => $self->{domain},
class => $class,
key => $key,
fid => $opts->{fid} || 0, # fid should be specified, or pass 0 meaning to auto-generate one
multi_dest => 1,
}
) or return undef;
my $dests = []; # [ [devid,path], [devid,path], ... ]
# determine old vs. new format to populate destinations
unless (exists $res->{dev_count}) {
push @$dests, [ $res->{devid}, $res->{path} ];
} else {
for my $i (1..$res->{dev_count}) {
push @$dests, [ $res->{"devid_$i"}, $res->{"path_$i"} ];
}
}
my ($length, $error, $devid, $path);
my @dests = (@$dests, @$dests, @$dests); # 2 retries
my $try = 0;
foreach my $dest (@dests) {
$try++;
($devid, $path) = @$dest;
my $uri = URI->new($path);
my $cv = AnyEvent->condvar;
my ($socket_guard, $socket_fh);
$socket_guard = tcp_connect $uri->host, $uri->port, sub {
my ($fh, $host, $port) = @_;
$error = $!;
if (!$fh) {
$cv->send;
return;
}
$socket_fh = $fh;
setsockopt($socket_fh, IPPROTO_TCP, TCP_CORK, 1) or warn "could not set TCP_CORK" if TCP_CORK;
$cv->send;
}, sub { 10 };
$cv->recv;
if (! $socket_fh) {
$error ||= 'unknown error';
warn("Connection error: $error to $path");
next;
}
undef $error;
# We are connected!
open my $fh_from, "<", $file or confess("Could not open $file");
# Hint to Linux that doubling readahead will probably pay off.
fadvise($fh_from, 0, 0, IO::AIO::FADV_SEQUENTIAL());
$length = -s $file;
my $buf = 'PUT ' . $uri->path . " HTTP/1.0\r\nConnection: close\r\nContent-Length: $length\r\n\r\n";
$cv = AnyEvent->condvar;
my $w;
my $timeout;
my $reset_timer = sub {
my ($type, $time) = @_;
$type ||= 'unknown';
$time ||= 60;
my $start = time();
$timeout = AnyEvent->timer(
after => $time,
cb => sub {
undef $w;
my $took = time() - $start;
$error = "Connection timed out duing data transfer of type $type (after $took seconds)";
$cv->send;
},
);
};
$w = AnyEvent->io( fh => $socket_fh, poll => 'w', cb => sub {
$reset_timer->('read');
if (!length($buf)) {
my $bytes = sysread $fh_from, $buf, '4096';
$reset_timer->('write');
if (!defined $bytes) { # Error, read FH blocking, no need to check EAGAIN
$error = $!;
$cv->send;
return;
}
if (0 == $bytes) { # EOF reading, and we already wrote everything
$cv->send;
return;
}
}
my $len = syswrite $socket_fh, $buf;
$reset_timer->('loop');
if ($len && $len > 0) {
$buf = substr $buf, $len;
}
if (!defined $len && $! != EAGAIN) { # Error, we could get EAGAIN as write sock non-blocking
$error = $!;
$cv->send;
return;
}
});
$reset_timer->('start PUT');
$cv->recv;
setsockopt($socket_fh, IPPROTO_TCP, TCP_CORK, 0) or warn "could not unset TCP_CORK" if TCP_CORK;
$cv = AnyEvent->condvar;
# FIXME - Cheat here, the response should be small, so we assume it'll allways all be
# readable at once, THIS MAY NOT BE TRUE!!!
$w = AnyEvent->io( fh => $socket_fh, poll => 'r', cb => sub {
undef $timeout;
undef $w;
$cv->send;
my $buf;
do {
if ($socket_fh->eof) {
$error = "Connection closed unexpectedly without response";
return;
}
my $res; $socket_fh->read($res, 4096); $buf .= $res;
} while (!length($buf));
my ($top, @headers) = split /\r?\n/, $buf;
if ($top =~ m{HTTP/1.[01]\s+2\d\d}) {
# Woo, 200!
undef $error;
}
else {
$error = "Got non-200 from remote server $top";
}
});
$reset_timer->('response', 1200); # Wait up to 20m, as lighty
# may have to copy the file between
# disks. EWWWW
$cv->recv;
undef $timeout;
if ($error) {
warn("Error sending data (try $try) to $uri: $error");
next; # Retry
}
last; # Success
}
die("Could not write to any mogile hosts, should have tried " . scalar(@$dests) . " did try $try")
if $error;
$self->run_hook('new_file_end', $self, $key, $class, $opts);
my $rv = $self->{backend}->do_request
("create_close", {
fid => $res->{fid},
devid => $devid,
domain => $self->{domain},
size => $length,
key => $key,
path => $path,
});
unless ($rv) {
die "$self->{backend}->{lasterr}: $self->{backend}->{lasterrstr}";
return undef;
}
$self->run_hook('store_file_end', $self, $key, $class, $opts);
return $length;
}
sub store_content {
my MogileFS::Client $self = shift;
return undef if $self->{readonly};
my($key, $class, $content, $opts) = @_;
$self->run_hook('store_content_start', $self, $key, $class, $opts);
my $fh = $self->new_file($key, $class, undef, $opts) or return;
$content = ref($content) eq 'SCALAR' ? $$content : $content;
$fh->print($content);
$self->run_hook('store_content_end', $self, $key, $class, $opts);
$fh->close or return;
length($content);
}
1;