Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

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.

AWS reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
#  Private configuration, not a file in public web content or source control.
#  Load current IAM credentials authorized for the Glacier operation.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/glacier.json")
if (success != true)
    print "Could not load private AWS credentials." + "\n";
    exit
end

if ((credentials.JsonTypeOf("access_key") != 1) or (credentials.stringOf("access_key") == ""))
    print "Missing or invalid access_key." + "\n";
    exit
end

if ((credentials.JsonTypeOf("secret_key") != 1) or (credentials.stringOf("secret_key") == ""))
    print "Missing or invalid secret_key." + "\n";
    exit
end

#  Set this once to the region containing the vault.
region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("glacier.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("glacier")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure AWS signing." + "\n";
    exit
end

#  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") == true)
    if (credentials.JsonTypeOf("session_token") != 1)
        print "session_token must be a string." + "\n";
        exit
    end

    if (credentials.stringOf("session_token") != "")
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
        if (success != true)
            print "Could not set the session-token parameter." + "\n";
            exit
        end

    end

end

#  Supply a Socket to explicitly enable TLS certificate verification.
connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach the TLS connection." + "\n";
    exit
end

success = rest.AddHeader("x-amz-glacier-version","2012-06-01")
if (success != true)
    print "Could not set x-amz-glacier-version." + "\n";
    exit
end

#  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 != true)
    print "Could not set vault name." + "\n";
    exit
end

result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
error = Chilkat::CkJsonObject.new()
error.put_Strict(true)
responseBody = Chilkat::CkStringBuilder.new()
jobId = "YOUR_JOB_ID"
success = rest.AddPathParam("{job}",jobId)
if (success != true)
    print "Could not set job ID." + "\n";
    exit
end

success = rest.FullRequestNoBodySb("GET","/-/vaults/{vault}/jobs/{job}",responseBody)
if (success != true)
    print "Request did not complete; inspect diagnostics privately. Check state before retrying a change." + "\n";
    exit
end

if (rest.get_ResponseStatusCode() != 200)
    print "Glacier HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    success = error.LoadSb(responseBody)
    if (success == true)
        if (error.JsonTypeOf("code") == 1)
            print "AWS error code: " + error.stringOf("code") + "\n";
        end

    end

    print "AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId") + "\n";
    #  Inspect full errors privately. An HTTP error is not a successful operation.
    exit
end

success = result.LoadSb(responseBody)
if (success != true)
    print "Expected valid JSON response." + "\n";
    exit
end

if (result.JsonTypeOf("Completed") != 5)
    print "Missing or invalid Completed." + "\n";
    exit
end

if (result.JsonTypeOf("StatusCode") != 1)
    print "Missing or invalid StatusCode." + "\n";
    exit
end

if (result.stringOf("StatusCode") == "")
    print "Empty StatusCode." + "\n";
    exit
end

if ((result.BoolOf("Completed") != true) or (result.stringOf("StatusCode") != "Succeeded"))
    print "Job is not successfully complete. Resume later only if InProgress." + "\n";
    exit
end

if (result.stringOf("Action") != "ArchiveRetrieval")
    print "Wrong job type." + "\n";
    exit
end

if (result.JsonTypeOf("SHA256TreeHash") != 1)
    print "Missing or invalid SHA256TreeHash." + "\n";
    exit
end

if (result.stringOf("SHA256TreeHash") == "")
    print "Empty SHA256TreeHash." + "\n";
    exit
end

if (result.JsonTypeOf("ArchiveSizeInBytes") != 2)
    print "Missing or invalid ArchiveSizeInBytes." + "\n";
    exit
end

if (result.JsonTypeOf("ArchiveId") != 1)
    print "Missing or invalid ArchiveId." + "\n";
    exit
end

if (result.stringOf("ArchiveId") == "")
    print "Empty ArchiveId." + "\n";
    exit
end

if (result.JsonTypeOf("ArchiveSHA256TreeHash") != 1)
    print "Missing or invalid ArchiveSHA256TreeHash." + "\n";
    exit
end

if (result.stringOf("ArchiveSHA256TreeHash") == "")
    print "Empty ArchiveSHA256TreeHash." + "\n";
    exit
end

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
end

#  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 = Chilkat::CkStringBuilder.new()
decimalDigits = Chilkat::CkStringBuilder.new()
digit = Chilkat::CkStringBuilder.new()
sizeText.Append(expectedSize)
decimalDigits.Append("0123456789")
if ((sizeText.get_Length() == 0) or (sizeText.get_Length() > 14))
    print "Invalid archive size." + "\n";
    exit
end

while (position < sizeText.get_Length())
    digit.SetString(sizeText.getRange(position,1,false))
    if (decimalDigits.Contains(digit.getAsString(),true) != true)
        print "Invalid decimal archive size." + "\n";
        exit
    end

    remainder = remainder * 10 + digit.get_IntValue()
    #  At most nine subtractions per digit; avoids language-specific division.
    chunkCount = chunkCount * 10
    while (remainder >= chunkSize)
        chunkCount = chunkCount + 1
        remainder = remainder - chunkSize
    end
    position = position + 1
end
if ((chunkCount > 5242880) or ((chunkCount == 5242880) and (remainder != 0)))
    print "Archive exceeds the 40 TiB service limit." + "\n";
    exit
end

if ((chunkCount == 0) and (remainder == 0))
    print "Use the single-download example for an empty archive." + "\n";
    exit
end

if (remainder != 0)
    chunkCount = chunkCount + 1
end

#  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 = Chilkat::CkFileAccess.new()
success = files.DirEnsureExists(cacheDir)
if (success != true)
    print "Could not create private download directory." + "\n";
    exit
end

path = Chilkat::CkStringBuilder.new()
path.Append(cacheDir)
path.Append("/manifest.json")
manifestPath = path.getAsString()
manifest = Chilkat::CkJsonObject.new()
manifest.put_Strict(true)
identity = Chilkat::CkJsonObject.new()
success = identity.UpdateString("version","1")
if (success != true)
    print "Could not set version." + "\n";
    exit
end

success = identity.UpdateString("region",region)
if (success != true)
    print "Could not set region." + "\n";
    exit
end

success = identity.UpdateString("vault","chilkat")
if (success != true)
    print "Could not set vault." + "\n";
    exit
end

success = identity.UpdateString("jobId",jobId)
if (success != true)
    print "Could not set jobId." + "\n";
    exit
end

success = identity.UpdateString("archiveId",result.stringOf("ArchiveId"))
if (success != true)
    print "Could not set archiveId." + "\n";
    exit
end

success = identity.UpdateString("size",expectedSize)
if (success != true)
    print "Could not set size." + "\n";
    exit
end

success = identity.UpdateString("treeHash",expectedHash)
if (success != true)
    print "Could not set treeHash." + "\n";
    exit
end

success = identity.UpdateString("chunkSize","8388608")
if (success != true)
    print "Could not set chunkSize." + "\n";
    exit
end

success = identity.UpdateString("finalPath",finalPath)
if (success != true)
    print "Could not set finalPath." + "\n";
    exit
end

if (files.FileExists(manifestPath) == true)
    success = manifest.LoadFile(manifestPath)
    if (success != true)
        print "Invalid checkpoint. Preserve the cache and inspect it before restarting." + "\n";
        exit
    end

    if (manifest.stringOf("version") != identity.stringOf("version"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("region") != identity.stringOf("region"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("vault") != identity.stringOf("vault"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("jobId") != identity.stringOf("jobId"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("archiveId") != identity.stringOf("archiveId"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("size") != identity.stringOf("size"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("treeHash") != identity.stringOf("treeHash"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("chunkSize") != identity.stringOf("chunkSize"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

    if (manifest.stringOf("finalPath") != identity.stringOf("finalPath"))
        print "Checkpoint belongs to different download settings. Use a new empty cache directory." + "\n";
        exit
    end

else
    cacheContents = Chilkat::CkDirTree.new()
    cacheContents.put_BaseDir(cacheDir)
    cacheContents.put_Recurse(false)
    success = cacheContents.BeginIterate()
    if ((success == true) or (cacheContents.get_DoneIterating() != true))
        print "First run requires an empty, readable cache directory." + "\n";
        exit
    end

    success = identity.WriteFile(manifestPath)
    if (success != true)
        print "Could not save download identity." + "\n";
        exit
    end

end

crypt = Chilkat::CkCrypt2.new()
crypt.put_HashAlgorithm("sha256-tree-hash")
crypt.put_EncodingMode("hexlower")
if (files.FileExists(finalPath) == true)
    finalSize = files.fileSizeStr(finalPath)
    finalHash = crypt.hashFileENC(finalPath)
    if ((crypt.get_LastMethodSuccess() != true) or (finalSize != expectedSize) or (finalHash != expectedHash))
        print "Existing final file differs; choose another final output path." + "\n";
        exit
    end

    print "Archive already downloaded and verified." + "\n";
    exit
end

rangeHeader = Chilkat::CkStringBuilder.new()
contentRange = Chilkat::CkStringBuilder.new()
byteCount = Chilkat::CkStringBuilder.new()
receipt = Chilkat::CkJsonObject.new()
receipt.put_Strict(true)
chunkIndex = 0
byteHigh = 0
byteLow = 0

range = Chilkat::CkStringBuilder.new()
digits = Chilkat::CkStringBuilder.new()
while (chunkIndex < chunkCount)
    chunkBytes = chunkSize
    if ((chunkIndex == chunkCount - 1) and (remainder != 0))
        chunkBytes = remainder
    end

    range.Clear()
    digits.Clear()
    digits.AppendInt(byteLow)
    if (byteHigh > 0)
        while (digits.get_Length() < 9)
            digits.Prepend("0")
        end
        range.AppendInt(byteHigh)
    end

    range.Append(digits.getAsString())
    range.Append("-")
    endHigh = byteHigh
    endLow = byteLow + chunkBytes - 1
    if (endLow >= 1000000000)
        endLow = endLow - 1000000000
        endHigh = endHigh + 1
    end

    digits.Clear()
    digits.AppendInt(endLow)
    if (endHigh > 0)
        while (digits.get_Length() < 9)
            digits.Prepend("0")
        end
        range.AppendInt(endHigh)
    end

    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) == true)
        success = receipt.LoadFile(receiptPath)
        if (success != true)
            print "Cached chunk lacks a valid receipt. Preserve the cache and inspect it." + "\n";
            exit
        end

        cachedHash = crypt.hashFileENC(chunkPath)
        if ((crypt.get_LastMethodSuccess() != true) 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
        end

        print "Reusing verified chunk: " + chunkIndex.to_s() + "\n";
    else
        success = rest.AddHeader("Range",rangeHeader.getAsString())
        if (success != true)
            print "Could not set Range." + "\n";
            exit
        end

        success = rest.SendReqNoBody("GET","/-/vaults/{vault}/jobs/{job}/output")
        if (success != true)
            print "Could not send range request. Rerun to resume." + "\n";
            exit
        end

        httpStatus = rest.ReadResponseHeader()
        if (httpStatus != 206)
            print "Expected HTTP 206 for range download. Job may have expired; no new retrieval was started." + "\n";
            exit
        end

        responseRange = rest.responseHdrByName("Content-Range")
        if ((rest.get_LastMethodSuccess() != true) or (responseRange != contentRange.getAsString()))
            print "Unexpected Content-Range; refusing download." + "\n";
            exit
        end

        responseLength = rest.responseHdrByName("Content-Length")
        if ((rest.get_LastMethodSuccess() != true) or (responseLength != byteCount.getAsString()))
            print "Unexpected Content-Length; refusing download." + "\n";
            exit
        end

        responseHash = rest.responseHdrByName("x-amz-sha256-tree-hash")
        if ((rest.get_LastMethodSuccess() != true) or (responseHash == ""))
            print "Missing range tree hash. Require a tree-hash-aligned retrieval and download range." + "\n";
            exit
        end

        output = Chilkat::CkStream.new()
        output.put_SinkFile(temporaryPath)
        success = rest.ReadRespBodyStream(output,true)
        if (success != true)
            print "Download interrupted; rerun to resume. Temporary bytes are not trusted." + "\n";
            exit
        end

        actualSize = files.fileSizeStr(temporaryPath)
        if ((files.get_LastMethodSuccess() != true) or (actualSize != byteCount.getAsString()))
            print "Downloaded size mismatch." + "\n";
            exit
        end

        actualHash = crypt.hashFileENC(temporaryPath)
        if ((crypt.get_LastMethodSuccess() != true) or (actualHash != responseHash))
            print "Downloaded tree hash mismatch." + "\n";
            exit
        end

        success = receipt.UpdateString("range",rangeKey)
        if (success != true)
            print "Could not set range." + "\n";
            exit
        end

        success = receipt.UpdateString("treeHash",actualHash)
        if (success != true)
            print "Could not set treeHash." + "\n";
            exit
        end

        success = receipt.WriteFile(receiptPath)
        if (success != true)
            print "Could not save chunk checksum; temporary bytes remain uncommitted." + "\n";
            exit
        end

        success = files.FileRename(temporaryPath,chunkPath)
        if (success != true)
            print "Could not commit verified chunk." + "\n";
            exit
        end

        print "Downloaded verified chunk: " + chunkIndex.to_s() + "\n";
    end

    byteHigh = endHigh
    byteLow = endLow + 1
    if (byteLow == 1000000000)
        byteLow = 0
        byteHigh = byteHigh + 1
    end

    chunkIndex = chunkIndex + 1
end
#  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 = Chilkat::CkFileAccess.new()
success = assembled.OpenForWrite(assembledPath)
if (success != true)
    print "Could not open assembly file." + "\n";
    exit
end

data = Chilkat::CkBinData.new()
chunkIndex = 0
while (chunkIndex < chunkCount)
    path.SetString(cacheDir)
    path.Append("/chunk-")
    path.AppendInt(chunkIndex)
    data.Clear()
    success = data.LoadFile(path.getAsString())
    if (success == true)
        success = assembled.FileWriteBd(data,0,0)
    end

    if (success != true)
        assembled.FileClose()
        print "Assembly failed. Verified chunks are retained for resume." + "\n";
        exit
    end

    chunkIndex = chunkIndex + 1
end
assembled.FileClose()
assembledSize = files.fileSizeStr(assembledPath)
assembledHash = crypt.hashFileENC(assembledPath)
if ((crypt.get_LastMethodSuccess() != true) or (assembledSize != expectedSize) or (assembledHash != expectedHash))
    print "Assembled archive failed verification; final output was not created." + "\n";
    exit
end

success = files.FileRename(assembledPath,finalPath)
if (success != true)
    print "Verified assembly could not be renamed; keep the cache." + "\n";
    exit
end

print "Archive downloaded and verified. Retained chunks can now be removed manually." + "\n";