my $fileObj = $schema->resultset('Files')->some_query() # A DBIx::Class result object. my $ua: # An LWP::UserAgent instance HOST: foreach my $host ( @hosts2try ) { my $leafname = $fileObj->leafname(); my $file_url = 'http://'.$host.'/'.$leafname; $logger->debug("Will try fetching $leafname from $host"); # First check if the remote host has the file & the size is correct. my $response = $ua->head($file_url); if( ! $response->is_success() ) { # Not a problem as not every host has every file. $logger->debug("Looks like $host does not have $leafname. Will try another host"); next HOST; } elsif( $imageObj->size() != $response->headers->header('content-length') ) { # An error. If a host has a file it should be correct. my $remote_size = $response->headers->header('content-length'); $logger->error("Host $host has a copy of $leafname but the size is wrong. Is $remote_size bytes but should be ".$imageObj->size() ); next HOST; } # Looks like the remote server has the file. Download it. $logger->info('Fetching '.$file_url); $ua->get($file_url, ':content_file' => $tmp_path); if( -f $tmp_path ) { if( ( $imageObj->size() == -s $tmp_path ) && ( $imageObj->checksum() eq get_sha1_checksum($tmp_path) ) ) { $logger->info("Successfully fetched $filename from $file_url"); move($tmp_path, $final_path); return 1; } else { $logger->error("Serious: $filename fetched from $file_url was truncated or corrupt") unlink $tmp_path; next HOST; } } else { $logger->error('Error fetching: '.$file_url); next HOST; } }