-
Notifications
You must be signed in to change notification settings - Fork 14
/
Object.pm
582 lines (446 loc) · 17 KB
/
Object.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package WebService::Rackspace::CloudFiles::Object;
use Moo;
use MooX::StrictConstructor;
use Types::Standard qw(Bool Str StrMatch Num Int HashRef InstanceOf);
use Digest::MD5 qw(md5_hex);
use Digest::MD5::File qw(file_md5_hex);
use File::stat;
use Carp qw(confess);
use WebService::Rackspace::CloudFiles::DateTime;
has 'cloudfiles' =>
( is => 'ro', isa => InstanceOf['WebService::Rackspace::CloudFiles'], required => 1 );
has 'container' =>
( is => 'ro', isa => InstanceOf['WebService::Rackspace::CloudFiles::Container'], required => 1 );
has 'name' => ( is => 'ro', isa => Str, required => 1 );
has 'etag' => ( is => 'rw', isa => StrMatch[qr/^[a-z0-9]{32}$/] );
has 'size' => ( is => 'rw', isa => Int );
has 'content_type' =>
( is => 'rw', isa => Str, default => 'binary/octet-stream' );
has 'last_modified' => (
is => 'rw',
isa => InstanceOf['WebService::Rackspace::CloudFiles::DateTime'],
coerce => sub {
my $val = shift;
$val = DateTime::Format::HTTP->parse_datetime($val) unless ref $val;
bless $val, 'WebService::Rackspace::CloudFiles::DateTime';
return $val;
}
);
has 'cache_value' => (
is => 'rw',
isa => Bool,
required => 1,
default => 0
);
has 'always_check_etag' => (
is => 'rw',
isa => Bool,
required => 1,
default => 1
);
has 'object_metadata' => (
is => 'rw',
isa => HashRef,
required => 0,
default => sub {
return {};
}
);
has 'value' => (
is => 'rw',
required => 0,
default => undef,
);
has 'local_filename' => (
is => 'rw',
isa => Str,
required => 0
);
__PACKAGE__->meta->make_immutable;
sub _url {
my ($self) = @_;
my $url
= $self->cloudfiles->storage_url . '/'
. $self->container->name . '/'
. $self->name;
utf8::downgrade($url);
return $url;
}
# get the CDN management url for this object (for edge purge)
sub _management_url {
my ($self) = @_;
my $url
= $self->cloudfiles->cdn_management_url . "/"
. $self->container->name . '/'
. $self->name;
utf8::downgrade($url);
return $url;
}
sub _cdn_url {
my($self,$ssl) = @_;
$ssl ||= 0;
return sprintf('%s/%s',
$ssl ? $self->container->cdn_ssl_uri : $self->container->cdn_uri,
$self->name);
}
sub cdn_url {
return shift->_cdn_url;
}
sub cdn_ssl_url {
return shift->_cdn_url(1);
}
sub head {
my $self = shift;
my $request = HTTP::Request->new( 'HEAD', $self->_url,
[ 'X-Auth-Token' => $self->cloudfiles->token ] );
my $response = $self->cloudfiles->_request($request);
confess 'Object ' . $self->name . ' not found' if $response->code == 404;
confess 'Unknown error' unless $response->is_success;
$self->_set_attributes_from_response($response);
return $response->content;
}
sub get {
my ($self, $force_retrieval) = @_;
if (!$force_retrieval && $self->cache_value() && defined($self->value()) ) {
return $self->value();
} else {
my $request = HTTP::Request->new( 'GET', $self->_url,
[ 'X-Auth-Token' => $self->cloudfiles->token ] );
my $response = $self->cloudfiles->_request($request);
confess 'Object ' . $self->name . ' not found' if $response->code == 404;
confess 'Unknown error' if !$response->is_success;
confess 'Data corruption error'
if $response->header('ETag') ne md5_hex( $response->content );
$self->_set_attributes_from_response($response);
if ($self->cache_value()) {
$self->value($response->content);
}
return $response->content();
}
}
sub get_filename {
my ( $self, $filename, $force_retrieval ) = @_;
## if we aren't forcing retrieval, and we are caching values, and we have a local_filename
## defined and it matches the filename we were just given, and the local_filename actually
## exists on the filesystem... then we can think about using the cached value.
if (!$force_retrieval && $self->cache_value() && defined($self->local_filename()) &&
$self->local_filename() eq $filename && -e $self->local_filename() ) {
## in order to do this, we have to at least verify that the file we have matches
## the file on cloud-files. Best way to do that is to load the metadata and
## compare the etags.
$self->head();
if ($self->etag() eq file_md5_hex($filename)) {
## our local data matches what's in the cloud, we don't have to re-download
return $self->local_filename();
}
}
## if we are here, we have to download the file.
my $request = HTTP::Request->new( 'GET', $self->_url,
[ 'X-Auth-Token' => $self->cloudfiles->token ] );
my $response = $self->cloudfiles->_request( $request, $filename );
confess 'Object ' . $self->name . ' not found' if $response->code == 404;
confess 'Unknown error' if !$response->is_success;
confess 'Data corruption error' unless $self->_validate_local_file( $filename,
$response->header('Content-Length'),
$response->header('ETag') );
$self->_set_attributes_from_response($response);
my $last_modified = $self->last_modified->epoch;
# make sure the file has the same last modification time
utime $last_modified, $last_modified, $filename;
if ($self->cache_value()) {
$self->local_filename($filename);
}
return $filename;
}
sub delete {
my $self = shift;
my $request = HTTP::Request->new( 'DELETE', $self->_url,
[ 'X-Auth-Token' => $self->cloudfiles->token ] );
my $response = $self->cloudfiles->_request($request);
confess 'Object ' . $self->name . ' not found' if $response->code == 404;
confess 'Unknown error' if !$response->is_success;
}
sub purge_cdn {
my ($self, @emails) = @_;
my $request = HTTP::Request->new( 'DELETE', $self->_management_url,
[ 'X-Auth-Token' => $self->cloudfiles->token,
'X-Purge-Email' => join ', ', @emails] );
my $response = $self->cloudfiles->_request($request);
confess 'Not Found' if $response->code == 404;
confess 'Unauthorized request' if $response->code == 403;
confess 'Unknown error' if !$response->is_success;
}
sub put {
my ( $self, $value ) = @_;
my $name = $self->name;
my $md5_hex = md5_hex($value);
my $size = length($value);
my $request = HTTP::Request->new(
'PUT',
$self->_url,
$self->_prepare_headers($md5_hex, $size),
$value
);
my $response = $self->cloudfiles->_request($request);
if ($response->is_success) {
## since the value was set successfully, we can set all our instance data appropriately.
$self->etag($md5_hex);
$self->size($size);
if ($self->cache_value) {
$self->value($value);
}
return;
}
confess 'Missing Content-Length or Content-Type header'
if $response->code == 412;
confess 'Data corruption error' if $response->code == 422;
confess 'Data corruption error' if $response->header('ETag') ne $md5_hex;
confess 'Unknown error' unless $response->is_success;
}
sub put_filename {
my ( $self, $filename ) = @_;
my $name = $self->name;
my $md5_hex = file_md5_hex($filename);
my $stat = stat($filename) || confess("No $filename: $!");
my $size = $stat->size;
my $request = HTTP::Request->new(
'PUT',
$self->_url,
$self->_prepare_headers($md5_hex, $size),
$self->_content_sub($filename),
);
my $response = $self->cloudfiles->_request($request);
if ($response->is_success) {
$self->etag($md5_hex);
$self->size($size);
if ($self->cache_value) {
$self->local_filename($filename);
}
}
confess 'Missing Content-Length or Content-Type header'
if $response->code == 412;
confess 'Data corruption error' if $response->code == 422;
confess 'Data corruption error' if !defined($response->header('ETag')) ||
($response->header('ETag') ne $md5_hex);
confess 'Unknown error' unless $response->is_success;
}
my %Supported_headers = (
map { $_ => 1 }
'Content-Encoding',
'Content-Disposition',
'X-Object-Manifest',
'Access-Control-Allow-Origin',
'Access-Control-Allow-Credentials',
'Access-Control-Expose-Headers',
'Access-Control-Max-Age',
'Access-Control-Allow-Methods',
'Access-Control-Allow-Headers',
'Origin',
'Access-Control-Request-Method',
'Access-Control-Request-Headers',
);
sub _prepare_headers {
my ($self, $etag, $size) = @_;
my $headers = HTTP::Headers->new();
$headers->header('X-Auth-Token' => $self->cloudfiles->token );
$headers->header('Content-length' => $size );
$headers->header('ETag' => $etag );
$headers->header('Content-Type' => $self->content_type);
my $header_field;
foreach my $key (keys %{$self->object_metadata}) {
$header_field = $key;
$header_field = 'X-Object-Meta-' . $header_field
unless $Supported_headers{$header_field};
# make _'s -'s for header sending.
$header_field =~ s/_/-/g;
$headers->header($header_field => $self->object_metadata->{$key});
}
return $headers;
}
sub _content_sub {
my $self = shift;
my $filename = shift;
my $stat = stat($filename);
my $remaining = $stat->size;
my $blksize = $stat->blksize || 4096;
confess "$filename not a readable file with fixed size"
unless -r $filename and ( -f _ || $remaining );
my $fh = IO::File->new( $filename, 'r' )
or confess "Could not open $filename: $!";
$fh->binmode;
return sub {
my $buffer;
# upon retries the file is closed and we must reopen it
unless ( $fh->opened ) {
$fh = IO::File->new( $filename, 'r' )
or confess "Could not open $filename: $!";
$fh->binmode;
$remaining = $stat->size;
}
# warn "read remaining $remaining";
unless ( my $read = $fh->read( $buffer, $blksize ) ) {
# warn "read $read buffer $buffer remaining $remaining";
confess
"Error while reading upload content $filename ($remaining remaining) $!"
if $! and $remaining;
# otherwise, we found EOF
$fh->close
or confess "close of upload content $filename failed: $!";
$buffer ||= ''
; # LWP expects an emptry string on finish, read returns 0
}
$remaining -= length($buffer);
return $buffer;
};
}
sub _set_attributes_from_response {
my ( $self, $response ) = @_;
$self->etag( $response->header('ETag') );
$self->size( $response->header('Content-Length') );
$self->content_type( $response->header('Content-Type') );
$self->last_modified( $response->header('Last-Modified') );
my $metadata = {};
foreach my $headername ($response->headers->header_field_names) {
if ($headername =~ /^x-object-meta-(.*)/i) {
my $key = $1;
## undo our _ to - translation
$key =~ s/-/_/g;
$metadata->{lc($key)} = $response->header($headername);
}
}
$self->object_metadata($metadata);
}
sub _validate_local_file {
my ($self, $localfile, $size, $md5) = @_;
my $stat = stat($localfile);
my $localsize = $stat->size;
# first check size, if they are different, we don't need to bother with
# an expensive md5 calculation on the whole file.
if ($size != $localsize ) {
return 0;
}
if ($self->always_check_etag && ($md5 ne file_md5_hex($localfile))) {
return 0;
}
return 1;
}
1;
__END__
=head1 NAME
WebService::Rackspace::CloudFiles::Object - Represent a Cloud Files object
=head1 SYNOPSIS
# To create a new object
my $xxx = $container->object( name => 'XXX' );
$xxx->put('this is the value');
# To create a new object with the contents of a local file
my $yyy = $container->object( name => 'YYY', content_type => 'text/plain' );
$yyy->put_filename('README');
# To fetch an object:
my $xxx2 = $container->object( name => 'XXX' );
my $value = $xxx2->get;
say 'has name ' . $xxx2->name;
say 'has md5 ' . $xxx2->etag;
say 'has size ' . $xxx2->size;
say 'has content type ' . $xxx2->content_type;
say 'has last_modified ' . $xxx2->last_modified;
# To download an object to a local file
$yyy->get_filename('README.downloaded');
=head1 DESCRIPTION
This class represents an object in Cloud Files. It is created by
calling object or objects on a L<WebService::Rackspace::CloudFiles::Container> object.
=head1 METHODS
=head2 name
Returns the name of the object.
say 'has name ' . $object->name;
=head2 head
Fetches the metadata of the object:
$object->head;
=head2 always_check_etag
When set to true, forces md5 calculation on every file download and
compares it to the provided etag. This can be a very expensive operation,
especially on larger files. Setting always_check_etag to false will avoid the
checksum on the file and will validate the file transfer was complete by
comparing the file sizes after download. Defaults to true.
=head2 cache_value
When set to true, any values retrieved from the server will be cached
within the object, this allows you to continue to use the value
without re-retrieving it from CloudFiles repeatedly. Defaults to false.
=head2 get
Fetches the metadata and content of an object:
my $value = $object->get;
If cache_value is enabled, will not re-retrieve the value from CloudFiles.
To force re-retrieval, pass true to the get routine:
my $value = $object->get(1);
=head2 get_filename
Downloads the content of an object to a local file,
checks the integrity of the file, sets metadata in the object
and sets the last modified time of the file to the same as the object.
$object->get_filename('README.downloaded');
If cache_value is enabled and the file has already been retrieved and is
present on the filesystem with the filename provided, and the file size and
md5 hash of the local file match what is in CloudFiles, the file will not
be re-retrieved and the local file will be returned as-is. To force a
re-fetch of the file, pass a true value as the second arg to get_filename():
$object->get_filename('README.downloaded',1);
=head2 delete
Deletes an object:
$object->delete;
=head2 purge_cdn
Purges an object in a CDN enabled container without having to wait for the TTL
to expire.
$object->purge_cdn;
Purging an object in a CDN enabled container may take long time. So you can
optionally provide one or more emails to be notified after the object is
fully purged.
my @emails = ('foo@example.com', 'bar@example.com');
$object->purge_cdn(@emails);
=head2 put
Creates a new object:
my $xxx = $container->object( name => 'XXX' );
$xxx->put('this is the value');
=head2 put_filename
Creates a new object with the contents of a local file:
my $yyy = $container->object( name => 'YYY', content_type => 'text/plain' );
$yyy->put_filename('README');
=head2 etag
Returns the entity tag of the object, which is its MD5:
say 'has md5 ' . $object->etag;
=head2 size
Return the size of an object in bytes:
say 'has size ' . $object->size;
=head2 content_type
Return the content type of an object:
say 'has content type ' . $object->content_type;
=head2 last_modified
Return the last modified time of an object as a L<DateTime> object:
say 'has last_modified ' . $object->last_modified;
=head2 object_metadata
Sets or returns a hashref of metadata to be stored along with the file
in CloudFiles. This hashref must containe key => value pairs and values
must be scalar type, if you require storage of complex data, you will need
to flatten it in some way prior to setting it here. Also, due to the way
that CloudFiles works with metadata, when retrieved from CloudFiles, your
keys will be lowercase. Note that since underscores are not permitted in
keys within CloudFiles, any underscores are translated to dashes when
transmitted to CloudFiles. They are re-translated when they are retrieved.
This is mentioned only because if you access your data through a different
language or interface, your metadata keys will contain dashes instead of
underscores.
=head2 cdn_url
Retrieve HTTP CDN url to object.
=head2 cdn_ssl_url
Retrieve HTTPS CDN url to object.
=head2 cloudfiles
=head2 container
=head2 value
=head1 SEE ALSO
L<WebService::Rackspace::CloudFiles>, L<WebService::Rackspace::CloudFiles::Container>.
=head1 AUTHORS
Christiaan Kras <ckras@cpan.org>.
Leon Brocard <acme@astray.com>.
=head1 COPYRIGHT
Copyright (C) 2010-2011, Christiaan Kras
Copyright (C) 2008-9, Leon Brocard
=head1 LICENSE
This module is free software; you can redistribute it or modify it
under the same terms as Perl itself.