Amazon Glacier: Resume an Archive Download with Verified Chunks
See more Amazon Glacier Examples
For existing Amazon Glacier vault customers. The standalone vault service is closed to new customers. These examples use its REST API version 2012-06-01, not the S3 bucket APIs used by S3 Glacier storage classes. See AWS service guidance.
Downloads a completed full-archive retrieval job in fixed 8 MiB ranges. Set the job ID, cache directory, and final path. Start with an empty, private cache directory on the same filesystem as the final output, then rerun with exactly the same settings to resume. Only one process may use the directory. No new retrieval job is initiated, even if the old job expires.
A saved identity binds progress to region, vault, job, archive ID, size, tree hash, chunk size, and final path. Every cached chunk is rehashed and its length and range checked before reuse. New chunks require HTTP 206, exact Content-Range and Content-Length, actual length, and a matching response tree hash before their temporary file is committed. An interrupted chunk is downloaded again; already verified chunks are retained. A damaged checkpoint or cached chunk stops with an explanation. Local cache files and receipts must be protected from other writers.
After downloading, the example assembles one chunk at a time and checks the entire file's byte count and archive tree hash before renaming it. Interrupted assembly is rebuilt from the cache. Existing final output is accepted only if it matches; other files are not overwritten. Chunks remain for inspection or manual cleanup. Allow disk space for both the complete chunk cache and assembled archive, plus one temporary chunk. A disk-full, network, or checksum failure is not success.
Uses decimal strings and bounded 32-bit arithmetic for archive offsets through the 40 TiB archive limit, including beyond 2 GiB. This produces up to 5,242,880 chunk files plus receipts at that limit; larger power-of-two chunks are more practical for very large archives, but require adapting the arithmetic and checkpoint schema. Empty archives use the single-download example. For partial retrieval jobs use range output download instead.
Requires glacier:DescribeJob and glacier:GetJobOutput. Resume promptly while output is retained (at least 24 hours after successful completion). If it has expired, initiate a new retrieval deliberately and use a new cache directory; cached chunks are not automatically transferred to a different job.
Uses AWS Signature Version 4 with service glacier. Set the region once; the example builds the commercial AWS endpoint. Other partitions require the appropriate endpoint suffix. /-/ selects the signing account; change the vault name and IDs to your own resources. Load private qa_data/aws/glacier.json with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles or refresh credentials. TLS certificate verification is enabled explicitly.
Checks transport completion, the operation-specific HTTP status, and parsed data separately. Inspect full diagnostics privately. Renew expired credentials; use bounded backoff with jitter for retryable reads. Uploads and job initiation can succeed before a connection fails, so do not blindly resubmit them. Configure IAM permissions for only the required operations and vault resources.
Chilkat PHP ActiveX Downloads
<?php
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/glacier.json');
if ($success != 1) {
print 'Could not load private AWS credentials.' . "\n";
exit;
}
if (($credentials->JsonTypeOf('access_key') != 1) or ($credentials->stringOf('access_key') == '')) {
print 'Missing or invalid access_key.' . "\n";
exit;
}
if (($credentials->JsonTypeOf('secret_key') != 1) or ($credentials->stringOf('secret_key') == '')) {
print 'Missing or invalid secret_key.' . "\n";
exit;
}
// Set this once to the region containing the vault.
$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('glacier.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'glacier';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
print 'Could not configure AWS signing.' . "\n";
exit;
}
// Temporary IAM/STS credentials require their session token on every signed request.
// Include the token in the signed query. Keep request URLs and diagnostics private.
// Leave session_token absent or empty only for credentials that do not have one.
if ($credentials->HasMember('session_token') == 1) {
if ($credentials->JsonTypeOf('session_token') != 1) {
print 'session_token must be a string.' . "\n";
exit;
}
if ($credentials->stringOf('session_token') != '') {
$success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
if ($success != 1) {
print 'Could not set the session-token parameter.' . "\n";
exit;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
print 'TLS connection failed; inspect diagnostics privately.' . "\n";
exit;
}
$success = $rest->UseConnection($connection,1);
if ($success != 1) {
print 'Could not attach the TLS connection.' . "\n";
exit;
}
$success = $rest->AddHeader('x-amz-glacier-version','2012-06-01');
if ($success != 1) {
print 'Could not set x-amz-glacier-version.' . "\n";
exit;
}
// A hyphen selects the account belonging to the signing credentials.
// Use the original, URL-safe vault name and IDs returned by Glacier.
$success = $rest->AddPathParam('{vault}','chilkat');
if ($success != 1) {
print 'Could not set vault name.' . "\n";
exit;
}
$result = new COM("Chilkat.JsonObject");
$result->Strict = 1;
$error = new COM("Chilkat.JsonObject");
$error->Strict = 1;
$responseBody = new COM("Chilkat.StringBuilder");
$jobId = 'YOUR_JOB_ID';
$success = $rest->AddPathParam('{job}',$jobId);
if ($success != 1) {
print 'Could not set job ID.' . "\n";
exit;
}
$success = $rest->FullRequestNoBodySb('GET','/-/vaults/{vault}/jobs/{job}',$responseBody);
if ($success != 1) {
print 'Request did not complete; inspect diagnostics privately. Check state before retrying a change.' . "\n";
exit;
}
if ($rest->ResponseStatusCode != 200) {
print 'Glacier HTTP status: ' . $rest->ResponseStatusCode . "\n";
$success = $error->LoadSb($responseBody);
if ($success == 1) {
if ($error->JsonTypeOf('code') == 1) {
print 'AWS error code: ' . $error->stringOf('code') . "\n";
}
}
print 'AWS request ID: ' . $rest->responseHdrByName('x-amzn-RequestId') . "\n";
// Inspect full errors privately. An HTTP error is not a successful operation.
exit;
}
$success = $result->LoadSb($responseBody);
if ($success != 1) {
print 'Expected valid JSON response.' . "\n";
exit;
}
if ($result->JsonTypeOf('Completed') != 5) {
print 'Missing or invalid Completed.' . "\n";
exit;
}
if ($result->JsonTypeOf('StatusCode') != 1) {
print 'Missing or invalid StatusCode.' . "\n";
exit;
}
if ($result->stringOf('StatusCode') == '') {
print 'Empty StatusCode.' . "\n";
exit;
}
if (($result->BoolOf('Completed') != 1) or ($result->stringOf('StatusCode') != 'Succeeded')) {
print 'Job is not successfully complete. Resume later only if InProgress.' . "\n";
exit;
}
if ($result->stringOf('Action') != 'ArchiveRetrieval') {
print 'Wrong job type.' . "\n";
exit;
}
if ($result->JsonTypeOf('SHA256TreeHash') != 1) {
print 'Missing or invalid SHA256TreeHash.' . "\n";
exit;
}
if ($result->stringOf('SHA256TreeHash') == '') {
print 'Empty SHA256TreeHash.' . "\n";
exit;
}
if ($result->JsonTypeOf('ArchiveSizeInBytes') != 2) {
print 'Missing or invalid ArchiveSizeInBytes.' . "\n";
exit;
}
if ($result->JsonTypeOf('ArchiveId') != 1) {
print 'Missing or invalid ArchiveId.' . "\n";
exit;
}
if ($result->stringOf('ArchiveId') == '') {
print 'Empty ArchiveId.' . "\n";
exit;
}
if ($result->JsonTypeOf('ArchiveSHA256TreeHash') != 1) {
print 'Missing or invalid ArchiveSHA256TreeHash.' . "\n";
exit;
}
if ($result->stringOf('ArchiveSHA256TreeHash') == '') {
print 'Empty ArchiveSHA256TreeHash.' . "\n";
exit;
}
$expectedSize = $result->stringOf('ArchiveSizeInBytes');
$expectedHash = $result->stringOf('ArchiveSHA256TreeHash');
if ($result->stringOf('SHA256TreeHash') != $expectedHash) {
print 'Use a full-archive retrieval job for this resumable example.' . "\n";
exit;
}
// Fixed 8 MiB chunks are power-of-two and tree-hash aligned.
// Decimal long division avoids 32-bit overflow in every generated language.
$chunkSize = 8388608;
$chunkCount = 0;
$remainder = 0;
$position = 0;
$sizeText = new COM("Chilkat.StringBuilder");
$decimalDigits = new COM("Chilkat.StringBuilder");
$digit = new COM("Chilkat.StringBuilder");
$sizeText->Append($expectedSize);
$decimalDigits->Append('0123456789');
if (($sizeText->Length == 0) or ($sizeText->Length > 14)) {
print 'Invalid archive size.' . "\n";
exit;
}
while (($position < $sizeText->Length)) {
$digit->SetString($sizeText->getRange($position,1,0));
if ($decimalDigits->Contains($digit->getAsString(),1) != 1) {
print 'Invalid decimal archive size.' . "\n";
exit;
}
$remainder = $remainder * 10 + $digit->IntValue;
// At most nine subtractions per digit; avoids language-specific division.
$chunkCount = $chunkCount * 10;
while (($remainder >= $chunkSize)) {
$chunkCount = $chunkCount + 1;
$remainder = $remainder - $chunkSize;
}
$position = $position + 1;
}
if (($chunkCount > 5242880) or (($chunkCount == 5242880) and ($remainder != 0))) {
print 'Archive exceeds the 40 TiB service limit.' . "\n";
exit;
}
if (($chunkCount == 0) and ($remainder == 0)) {
print 'Use the single-download example for an empty archive.' . "\n";
exit;
}
if ($remainder != 0) {
$chunkCount = $chunkCount + 1;
}
// This dedicated directory belongs to ONE job. Use a new empty directory
// when selecting another job. Run only one process against it at a time.
$cacheDir = 'qa_output/glacier-download';
$finalPath = 'qa_output/archive-resumed.dat';
$files = new COM("Chilkat.FileAccess");
$success = $files->DirEnsureExists($cacheDir);
if ($success != 1) {
print 'Could not create private download directory.' . "\n";
exit;
}
$path = new COM("Chilkat.StringBuilder");
$path->Append($cacheDir);
$path->Append('/manifest.json');
$manifestPath = $path->getAsString();
$manifest = new COM("Chilkat.JsonObject");
$manifest->Strict = 1;
$identity = new COM("Chilkat.JsonObject");
$success = $identity->UpdateString('version','1');
if ($success != 1) {
print 'Could not set version.' . "\n";
exit;
}
$success = $identity->UpdateString('region',$region);
if ($success != 1) {
print 'Could not set region.' . "\n";
exit;
}
$success = $identity->UpdateString('vault','chilkat');
if ($success != 1) {
print 'Could not set vault.' . "\n";
exit;
}
$success = $identity->UpdateString('jobId',$jobId);
if ($success != 1) {
print 'Could not set jobId.' . "\n";
exit;
}
$success = $identity->UpdateString('archiveId',$result->stringOf('ArchiveId'));
if ($success != 1) {
print 'Could not set archiveId.' . "\n";
exit;
}
$success = $identity->UpdateString('size',$expectedSize);
if ($success != 1) {
print 'Could not set size.' . "\n";
exit;
}
$success = $identity->UpdateString('treeHash',$expectedHash);
if ($success != 1) {
print 'Could not set treeHash.' . "\n";
exit;
}
$success = $identity->UpdateString('chunkSize','8388608');
if ($success != 1) {
print 'Could not set chunkSize.' . "\n";
exit;
}
$success = $identity->UpdateString('finalPath',$finalPath);
if ($success != 1) {
print 'Could not set finalPath.' . "\n";
exit;
}
if ($files->FileExists($manifestPath) == 1) {
$success = $manifest->LoadFile($manifestPath);
if ($success != 1) {
print 'Invalid checkpoint. Preserve the cache and inspect it before restarting.' . "\n";
exit;
}
if ($manifest->stringOf('version') != $identity->stringOf('version')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('region') != $identity->stringOf('region')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('vault') != $identity->stringOf('vault')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('jobId') != $identity->stringOf('jobId')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('archiveId') != $identity->stringOf('archiveId')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('size') != $identity->stringOf('size')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('treeHash') != $identity->stringOf('treeHash')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('chunkSize') != $identity->stringOf('chunkSize')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
if ($manifest->stringOf('finalPath') != $identity->stringOf('finalPath')) {
print 'Checkpoint belongs to different download settings. Use a new empty cache directory.' . "\n";
exit;
}
}
else {
$cacheContents = new COM("Chilkat.DirTree");
$cacheContents->BaseDir = $cacheDir;
$cacheContents->Recurse = 0;
$success = $cacheContents->BeginIterate();
if (($success == 1) or ($cacheContents->DoneIterating != 1)) {
print 'First run requires an empty, readable cache directory.' . "\n";
exit;
}
$success = $identity->WriteFile($manifestPath);
if ($success != 1) {
print 'Could not save download identity.' . "\n";
exit;
}
}
$crypt = new COM("Chilkat.Crypt2");
$crypt->HashAlgorithm = 'sha256-tree-hash';
$crypt->EncodingMode = 'hexlower';
if ($files->FileExists($finalPath) == 1) {
$finalSize = $files->fileSizeStr($finalPath);
$finalHash = $crypt->hashFileENC($finalPath);
if (($crypt->LastMethodSuccess != 1) or ($finalSize != $expectedSize) or ($finalHash != $expectedHash)) {
print 'Existing final file differs; choose another final output path.' . "\n";
exit;
}
print 'Archive already downloaded and verified.' . "\n";
exit;
}
$rangeHeader = new COM("Chilkat.StringBuilder");
$contentRange = new COM("Chilkat.StringBuilder");
$byteCount = new COM("Chilkat.StringBuilder");
$receipt = new COM("Chilkat.JsonObject");
$receipt->Strict = 1;
$chunkIndex = 0;
$byteHigh = 0;
$byteLow = 0;
$range = new COM("Chilkat.StringBuilder");
$digits = new COM("Chilkat.StringBuilder");
while (($chunkIndex < $chunkCount)) {
$chunkBytes = $chunkSize;
if (($chunkIndex == $chunkCount - 1) and ($remainder != 0)) {
$chunkBytes = $remainder;
}
$range->Clear();
$digits->Clear();
$digits->AppendInt($byteLow);
if ($byteHigh > 0) {
while (($digits->Length < 9)) {
$digits->Prepend('0');
}
$range->AppendInt($byteHigh);
}
$range->Append($digits->getAsString());
$range->Append('-');
$endHigh = $byteHigh;
$endLow = $byteLow + $chunkBytes - 1;
if ($endLow >= 1000000000) {
$endLow = $endLow - 1000000000;
$endHigh = $endHigh + 1;
}
$digits->Clear();
$digits->AppendInt($endLow);
if ($endHigh > 0) {
while (($digits->Length < 9)) {
$digits->Prepend('0');
}
$range->AppendInt($endHigh);
}
$range->Append($digits->getAsString());
$rangeKey = $range->getAsString();
$rangeHeader->SetString('bytes=');
$rangeHeader->Append($rangeKey);
$contentRange->SetString('bytes ');
$contentRange->Append($rangeKey);
$contentRange->Append('/');
$contentRange->Append($expectedSize);
$byteCount->Clear();
$byteCount->AppendInt($chunkBytes);
$path->SetString($cacheDir);
$path->Append('/chunk-');
$path->AppendInt($chunkIndex);
$chunkPath = $path->getAsString();
$path->Append('.json');
$receiptPath = $path->getAsString();
$path->SetString($chunkPath);
$path->Append('.part');
$temporaryPath = $path->getAsString();
if ($files->FileExists($chunkPath) == 1) {
$success = $receipt->LoadFile($receiptPath);
if ($success != 1) {
print 'Cached chunk lacks a valid receipt. Preserve the cache and inspect it.' . "\n";
exit;
}
$cachedHash = $crypt->hashFileENC($chunkPath);
if (($crypt->LastMethodSuccess != 1) or ($cachedHash != $receipt->stringOf('treeHash')) or ($receipt->stringOf('range') != $rangeKey) or ($files->fileSizeStr($chunkPath) != $byteCount->getAsString())) {
print 'Cached chunk failed verification. Remove only that chunk and its receipt, then rerun.' . "\n";
exit;
}
print 'Reusing verified chunk: ' . $chunkIndex . "\n";
}
else {
$success = $rest->AddHeader('Range',$rangeHeader->getAsString());
if ($success != 1) {
print 'Could not set Range.' . "\n";
exit;
}
$success = $rest->SendReqNoBody('GET','/-/vaults/{vault}/jobs/{job}/output');
if ($success != 1) {
print 'Could not send range request. Rerun to resume.' . "\n";
exit;
}
$httpStatus = $rest->ReadResponseHeader();
if ($httpStatus != 206) {
print 'Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.' . "\n";
exit;
}
$responseRange = $rest->responseHdrByName('Content-Range');
if (($rest->LastMethodSuccess != 1) or ($responseRange != $contentRange->getAsString())) {
print 'Unexpected Content-Range; refusing download.' . "\n";
exit;
}
$responseLength = $rest->responseHdrByName('Content-Length');
if (($rest->LastMethodSuccess != 1) or ($responseLength != $byteCount->getAsString())) {
print 'Unexpected Content-Length; refusing download.' . "\n";
exit;
}
$responseHash = $rest->responseHdrByName('x-amz-sha256-tree-hash');
if (($rest->LastMethodSuccess != 1) or ($responseHash == '')) {
print 'Missing range tree hash. Require a tree-hash-aligned retrieval and download range.' . "\n";
exit;
}
$output = new COM("Chilkat.Stream");
$output->SinkFile = $temporaryPath;
$success = $rest->ReadRespBodyStream($output,1);
if ($success != 1) {
print 'Download interrupted; rerun to resume. Temporary bytes are not trusted.' . "\n";
exit;
}
$actualSize = $files->fileSizeStr($temporaryPath);
if (($files->LastMethodSuccess != 1) or ($actualSize != $byteCount->getAsString())) {
print 'Downloaded size mismatch.' . "\n";
exit;
}
$actualHash = $crypt->hashFileENC($temporaryPath);
if (($crypt->LastMethodSuccess != 1) or ($actualHash != $responseHash)) {
print 'Downloaded tree hash mismatch.' . "\n";
exit;
}
$success = $receipt->UpdateString('range',$rangeKey);
if ($success != 1) {
print 'Could not set range.' . "\n";
exit;
}
$success = $receipt->UpdateString('treeHash',$actualHash);
if ($success != 1) {
print 'Could not set treeHash.' . "\n";
exit;
}
$success = $receipt->WriteFile($receiptPath);
if ($success != 1) {
print 'Could not save chunk checksum; temporary bytes remain uncommitted.' . "\n";
exit;
}
$success = $files->FileRename($temporaryPath,$chunkPath);
if ($success != 1) {
print 'Could not commit verified chunk.' . "\n";
exit;
}
print 'Downloaded verified chunk: ' . $chunkIndex . "\n";
}
$byteHigh = $endHigh;
$byteLow = $endLow + 1;
if ($byteLow == 1000000000) {
$byteLow = 0;
$byteHigh = $byteHigh + 1;
}
$chunkIndex = $chunkIndex + 1;
}
// Full-archive size plus hash protects against a partial retrieval job too.
// Assemble from verified chunks; interrupted assembly is rebuilt on rerun.
$path->SetString($cacheDir);
$path->Append('/assembled.part');
$assembledPath = $path->getAsString();
$assembled = new COM("Chilkat.FileAccess");
$success = $assembled->OpenForWrite($assembledPath);
if ($success != 1) {
print 'Could not open assembly file.' . "\n";
exit;
}
$data = new COM("Chilkat.BinData");
$chunkIndex = 0;
while (($chunkIndex < $chunkCount)) {
$path->SetString($cacheDir);
$path->Append('/chunk-');
$path->AppendInt($chunkIndex);
$data->Clear();
$success = $data->LoadFile($path->getAsString());
if ($success == 1) {
$success = $assembled->FileWriteBd($data,0,0);
}
if ($success != 1) {
$assembled->FileClose();
print 'Assembly failed. Verified chunks are retained for resume.' . "\n";
exit;
}
$chunkIndex = $chunkIndex + 1;
}
$assembled->FileClose();
$assembledSize = $files->fileSizeStr($assembledPath);
$assembledHash = $crypt->hashFileENC($assembledPath);
if (($crypt->LastMethodSuccess != 1) or ($assembledSize != $expectedSize) or ($assembledHash != $expectedHash)) {
print 'Assembled archive failed verification; final output was not created.' . "\n";
exit;
}
$success = $files->FileRename($assembledPath,$finalPath);
if ($success != 1) {
print 'Verified assembly could not be renamed; keep the cache.' . "\n";
exit;
}
print 'Archive downloaded and verified. Retained chunks can now be removed manually.' . "\n";
?>