Sample code for 30+ languages & platforms
Xojo Plugin 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 Xojo Plugin Downloads

Xojo Plugin
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean
success = False
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the Glacier operation.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/glacier.json")
If (success <> True) Then
    System.DebugLog("Could not load private AWS credentials.")
    Return
End If

If ((credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "")) Then
    System.DebugLog("Missing or invalid access_key.")
    Return
End If

If ((credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "")) Then
    System.DebugLog("Missing or invalid secret_key.")
    Return
End If

//  Set this once to the region containing the vault.
Dim region As String
region = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("glacier.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "glacier"
aws.SignatureVersion = 4
Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If (success <> True) Then
    System.DebugLog("Could not configure AWS signing.")
    Return
End If

//  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) Then
    If (credentials.JsonTypeOf("session_token") <> 1) Then
        System.DebugLog("session_token must be a string.")
        Return
    End If

    If (credentials.StringOf("session_token") <> "") Then
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
        If (success <> True) Then
            System.DebugLog("Could not set the session-token parameter.")
            Return
        End If

    End If

End If

//  Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
    System.DebugLog("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection,True)
If (success <> True) Then
    System.DebugLog("Could not attach the TLS connection.")
    Return
End If

success = rest.AddHeader("x-amz-glacier-version","2012-06-01")
If (success <> True) Then
    System.DebugLog("Could not set x-amz-glacier-version.")
    Return
End If

//  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) Then
    System.DebugLog("Could not set vault name.")
    Return
End If

Dim result As New Chilkat.JsonObject
result.Strict = True
Dim error As New Chilkat.JsonObject
error.Strict = True
Dim responseBody As New Chilkat.StringBuilder
Dim jobId As String
jobId = "YOUR_JOB_ID"
success = rest.AddPathParam("{job}",jobId)
If (success <> True) Then
    System.DebugLog("Could not set job ID.")
    Return
End If

success = rest.FullRequestNoBodySb("GET","/-/vaults/{vault}/jobs/{job}",responseBody)
If (success <> True) Then
    System.DebugLog("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
    Return
End If

If (rest.ResponseStatusCode <> 200) Then
    System.DebugLog("Glacier HTTP status: " + Str(rest.ResponseStatusCode))
    success = error.LoadSb(responseBody)
    If (success = True) Then
        If (error.JsonTypeOf("code") = 1) Then
            System.DebugLog("AWS error code: " + error.StringOf("code"))
        End If

    End If

    System.DebugLog("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"))
    //  Inspect full errors privately. An HTTP error is not a successful operation.
    Return
End If

success = result.LoadSb(responseBody)
If (success <> True) Then
    System.DebugLog("Expected valid JSON response.")
    Return
End If

If (result.JsonTypeOf("Completed") <> 5) Then
    System.DebugLog("Missing or invalid Completed.")
    Return
End If

If (result.JsonTypeOf("StatusCode") <> 1) Then
    System.DebugLog("Missing or invalid StatusCode.")
    Return
End If

If (result.StringOf("StatusCode") = "") Then
    System.DebugLog("Empty StatusCode.")
    Return
End If

If ((result.BoolOf("Completed") <> True) Or (result.StringOf("StatusCode") <> "Succeeded")) Then
    System.DebugLog("Job is not successfully complete. Resume later only if InProgress.")
    Return
End If

If (result.StringOf("Action") <> "ArchiveRetrieval") Then
    System.DebugLog("Wrong job type.")
    Return
End If

If (result.JsonTypeOf("SHA256TreeHash") <> 1) Then
    System.DebugLog("Missing or invalid SHA256TreeHash.")
    Return
End If

If (result.StringOf("SHA256TreeHash") = "") Then
    System.DebugLog("Empty SHA256TreeHash.")
    Return
End If

If (result.JsonTypeOf("ArchiveSizeInBytes") <> 2) Then
    System.DebugLog("Missing or invalid ArchiveSizeInBytes.")
    Return
End If

If (result.JsonTypeOf("ArchiveId") <> 1) Then
    System.DebugLog("Missing or invalid ArchiveId.")
    Return
End If

If (result.StringOf("ArchiveId") = "") Then
    System.DebugLog("Empty ArchiveId.")
    Return
End If

If (result.JsonTypeOf("ArchiveSHA256TreeHash") <> 1) Then
    System.DebugLog("Missing or invalid ArchiveSHA256TreeHash.")
    Return
End If

If (result.StringOf("ArchiveSHA256TreeHash") = "") Then
    System.DebugLog("Empty ArchiveSHA256TreeHash.")
    Return
End If

Dim expectedSize As String
expectedSize = result.StringOf("ArchiveSizeInBytes")
Dim expectedHash As String
expectedHash = result.StringOf("ArchiveSHA256TreeHash")
If (result.StringOf("SHA256TreeHash") <> expectedHash) Then
    System.DebugLog("Use a full-archive retrieval job for this resumable example.")
    Return
End If

//  Fixed 8 MiB chunks are power-of-two and tree-hash aligned.
//  Decimal long division avoids 32-bit overflow in every generated language.
Dim chunkSize As Int32
chunkSize = 8388608
Dim chunkCount As Int32
chunkCount = 0
Dim remainder As Int32
remainder = 0
Dim position As Int32
position = 0
Dim sizeText As New Chilkat.StringBuilder
Dim decimalDigits As New Chilkat.StringBuilder
Dim digit As New Chilkat.StringBuilder
success = sizeText.Append(expectedSize)
success = decimalDigits.Append("0123456789")
If ((sizeText.Length = 0) Or (sizeText.Length > 14)) Then
    System.DebugLog("Invalid archive size.")
    Return
End If

While (position < sizeText.Length)
    success = digit.SetString(sizeText.GetRange(position,1,False))
    If (decimalDigits.Contains(digit.GetAsString(),True) <> True) Then
        System.DebugLog("Invalid decimal archive size.")
        Return
    End If

    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
    Wend
    position = position + 1
Wend
If ((chunkCount > 5242880) Or ((chunkCount = 5242880) And (remainder <> 0))) Then
    System.DebugLog("Archive exceeds the 40 TiB service limit.")
    Return
End If

If ((chunkCount = 0) And (remainder = 0)) Then
    System.DebugLog("Use the single-download example for an empty archive.")
    Return
End If

If (remainder <> 0) Then
    chunkCount = chunkCount + 1
End If

//  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.
Dim cacheDir As String
cacheDir = "qa_output/glacier-download"
Dim finalPath As String
finalPath = "qa_output/archive-resumed.dat"
Dim files As New Chilkat.FileAccess
success = files.DirEnsureExists(cacheDir)
If (success <> True) Then
    System.DebugLog("Could not create private download directory.")
    Return
End If

Dim path As New Chilkat.StringBuilder
success = path.Append(cacheDir)
success = path.Append("/manifest.json")
Dim manifestPath As String
manifestPath = path.GetAsString()
Dim manifest As New Chilkat.JsonObject
manifest.Strict = True
Dim identity As New Chilkat.JsonObject
success = identity.UpdateString("version","1")
If (success <> True) Then
    System.DebugLog("Could not set version.")
    Return
End If

success = identity.UpdateString("region",region)
If (success <> True) Then
    System.DebugLog("Could not set region.")
    Return
End If

success = identity.UpdateString("vault","chilkat")
If (success <> True) Then
    System.DebugLog("Could not set vault.")
    Return
End If

success = identity.UpdateString("jobId",jobId)
If (success <> True) Then
    System.DebugLog("Could not set jobId.")
    Return
End If

success = identity.UpdateString("archiveId",result.StringOf("ArchiveId"))
If (success <> True) Then
    System.DebugLog("Could not set archiveId.")
    Return
End If

success = identity.UpdateString("size",expectedSize)
If (success <> True) Then
    System.DebugLog("Could not set size.")
    Return
End If

success = identity.UpdateString("treeHash",expectedHash)
If (success <> True) Then
    System.DebugLog("Could not set treeHash.")
    Return
End If

success = identity.UpdateString("chunkSize","8388608")
If (success <> True) Then
    System.DebugLog("Could not set chunkSize.")
    Return
End If

success = identity.UpdateString("finalPath",finalPath)
If (success <> True) Then
    System.DebugLog("Could not set finalPath.")
    Return
End If

If (files.FileExists(manifestPath) = True) Then
    success = manifest.LoadFile(manifestPath)
    If (success <> True) Then
        System.DebugLog("Invalid checkpoint. Preserve the cache and inspect it before restarting.")
        Return
    End If

    If (manifest.StringOf("version") <> identity.StringOf("version")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("region") <> identity.StringOf("region")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("vault") <> identity.StringOf("vault")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("jobId") <> identity.StringOf("jobId")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("archiveId") <> identity.StringOf("archiveId")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("size") <> identity.StringOf("size")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("treeHash") <> identity.StringOf("treeHash")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("chunkSize") <> identity.StringOf("chunkSize")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

    If (manifest.StringOf("finalPath") <> identity.StringOf("finalPath")) Then
        System.DebugLog("Checkpoint belongs to different download settings. Use a new empty cache directory.")
        Return
    End If

Else
    Dim cacheContents As New Chilkat.DirTree
    cacheContents.BaseDir = cacheDir
    cacheContents.Recurse = False
    success = cacheContents.BeginIterate()
    If ((success = True) Or (cacheContents.DoneIterating <> True)) Then
        System.DebugLog("First run requires an empty, readable cache directory.")
        Return
    End If

    success = identity.WriteFile(manifestPath)
    If (success <> True) Then
        System.DebugLog("Could not save download identity.")
        Return
    End If

End If

Dim crypt As New Chilkat.Crypt2
crypt.HashAlgorithm = "sha256-tree-hash"
crypt.EncodingMode = "hexlower"
If (files.FileExists(finalPath) = True) Then
    Dim finalSize As String
    finalSize = files.FileSizeStr(finalPath)
    Dim finalHash As String
    finalHash = crypt.HashFileENC(finalPath)
    If ((crypt.LastMethodSuccess <> True) Or (finalSize <> expectedSize) Or (finalHash <> expectedHash)) Then
        System.DebugLog("Existing final file differs; choose another final output path.")
        Return
    End If

    System.DebugLog("Archive already downloaded and verified.")
    Return
End If

Dim rangeHeader As New Chilkat.StringBuilder
Dim contentRange As New Chilkat.StringBuilder
Dim byteCount As New Chilkat.StringBuilder
Dim receipt As New Chilkat.JsonObject
receipt.Strict = True
Dim chunkIndex As Int32
chunkIndex = 0
Dim byteHigh As Int32
byteHigh = 0
Dim byteLow As Int32
byteLow = 0
Dim endHigh As Int32
Dim endLow As Int32
Dim range As New Chilkat.StringBuilder
Dim digits As New Chilkat.StringBuilder
While (chunkIndex < chunkCount)
    Dim chunkBytes As Int32
    chunkBytes = chunkSize
    If ((chunkIndex = chunkCount - 1) And (remainder <> 0)) Then
        chunkBytes = remainder
    End If

    range.Clear 
    digits.Clear 
    success = digits.AppendInt(byteLow)
    If (byteHigh > 0) Then
        While (digits.Length < 9)
            success = digits.Prepend("0")
        Wend
        success = range.AppendInt(byteHigh)
    End If

    success = range.Append(digits.GetAsString())
    success = range.Append("-")
    endHigh = byteHigh
    endLow = byteLow + chunkBytes - 1
    If (endLow >= 1000000000) Then
        endLow = endLow - 1000000000
        endHigh = endHigh + 1
    End If

    digits.Clear 
    success = digits.AppendInt(endLow)
    If (endHigh > 0) Then
        While (digits.Length < 9)
            success = digits.Prepend("0")
        Wend
        success = range.AppendInt(endHigh)
    End If

    success = range.Append(digits.GetAsString())
    Dim rangeKey As String
    rangeKey = range.GetAsString()
    success = rangeHeader.SetString("bytes=")
    success = rangeHeader.Append(rangeKey)
    success = contentRange.SetString("bytes ")
    success = contentRange.Append(rangeKey)
    success = contentRange.Append("/")
    success = contentRange.Append(expectedSize)
    byteCount.Clear 
    success = byteCount.AppendInt(chunkBytes)
    success = path.SetString(cacheDir)
    success = path.Append("/chunk-")
    success = path.AppendInt(chunkIndex)
    Dim chunkPath As String
    chunkPath = path.GetAsString()
    success = path.Append(".json")
    Dim receiptPath As String
    receiptPath = path.GetAsString()
    success = path.SetString(chunkPath)
    success = path.Append(".part")
    Dim temporaryPath As String
    temporaryPath = path.GetAsString()
    If (files.FileExists(chunkPath) = True) Then
        success = receipt.LoadFile(receiptPath)
        If (success <> True) Then
            System.DebugLog("Cached chunk lacks a valid receipt. Preserve the cache and inspect it.")
            Return
        End If

        Dim cachedHash As String
        cachedHash = crypt.HashFileENC(chunkPath)
        If ((crypt.LastMethodSuccess <> True) Or (cachedHash <> receipt.StringOf("treeHash")) Or (receipt.StringOf("range") <> rangeKey) Or (files.FileSizeStr(chunkPath) <> byteCount.GetAsString())) Then
            System.DebugLog("Cached chunk failed verification. Remove only that chunk and its receipt, then rerun.")
            Return
        End If

        System.DebugLog("Reusing verified chunk: " + Str(chunkIndex))
    Else
        success = rest.AddHeader("Range",rangeHeader.GetAsString())
        If (success <> True) Then
            System.DebugLog("Could not set Range.")
            Return
        End If

        success = rest.SendReqNoBody("GET","/-/vaults/{vault}/jobs/{job}/output")
        If (success <> True) Then
            System.DebugLog("Could not send range request. Rerun to resume.")
            Return
        End If

        Dim httpStatus As Int32
        httpStatus = rest.ReadResponseHeader()
        If (httpStatus <> 206) Then
            System.DebugLog("Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.")
            Return
        End If

        Dim responseRange As String
        responseRange = rest.ResponseHdrByName("Content-Range")
        If ((rest.LastMethodSuccess <> True) Or (responseRange <> contentRange.GetAsString())) Then
            System.DebugLog("Unexpected Content-Range; refusing download.")
            Return
        End If

        Dim responseLength As String
        responseLength = rest.ResponseHdrByName("Content-Length")
        If ((rest.LastMethodSuccess <> True) Or (responseLength <> byteCount.GetAsString())) Then
            System.DebugLog("Unexpected Content-Length; refusing download.")
            Return
        End If

        Dim responseHash As String
        responseHash = rest.ResponseHdrByName("x-amz-sha256-tree-hash")
        If ((rest.LastMethodSuccess <> True) Or (responseHash = "")) Then
            System.DebugLog("Missing range tree hash. Require a tree-hash-aligned retrieval and download range.")
            Return
        End If

        Dim output As New Chilkat.Stream
        output.SinkFile = temporaryPath
        success = rest.ReadRespBodyStream(output,True)
        If (success <> True) Then
            System.DebugLog("Download interrupted; rerun to resume. Temporary bytes are not trusted.")
            Return
        End If

        Dim actualSize As String
        actualSize = files.FileSizeStr(temporaryPath)
        If ((files.LastMethodSuccess <> True) Or (actualSize <> byteCount.GetAsString())) Then
            System.DebugLog("Downloaded size mismatch.")
            Return
        End If

        Dim actualHash As String
        actualHash = crypt.HashFileENC(temporaryPath)
        If ((crypt.LastMethodSuccess <> True) Or (actualHash <> responseHash)) Then
            System.DebugLog("Downloaded tree hash mismatch.")
            Return
        End If

        success = receipt.UpdateString("range",rangeKey)
        If (success <> True) Then
            System.DebugLog("Could not set range.")
            Return
        End If

        success = receipt.UpdateString("treeHash",actualHash)
        If (success <> True) Then
            System.DebugLog("Could not set treeHash.")
            Return
        End If

        success = receipt.WriteFile(receiptPath)
        If (success <> True) Then
            System.DebugLog("Could not save chunk checksum; temporary bytes remain uncommitted.")
            Return
        End If

        success = files.FileRename(temporaryPath,chunkPath)
        If (success <> True) Then
            System.DebugLog("Could not commit verified chunk.")
            Return
        End If

        System.DebugLog("Downloaded verified chunk: " + Str(chunkIndex))
    End If

    byteHigh = endHigh
    byteLow = endLow + 1
    If (byteLow = 1000000000) Then
        byteLow = 0
        byteHigh = byteHigh + 1
    End If

    chunkIndex = chunkIndex + 1
Wend
//  Full-archive size plus hash protects against a partial retrieval job too.
//  Assemble from verified chunks; interrupted assembly is rebuilt on rerun.
success = path.SetString(cacheDir)
success = path.Append("/assembled.part")
Dim assembledPath As String
assembledPath = path.GetAsString()
Dim assembled As New Chilkat.FileAccess
success = assembled.OpenForWrite(assembledPath)
If (success <> True) Then
    System.DebugLog("Could not open assembly file.")
    Return
End If

Dim data As New Chilkat.BinData
chunkIndex = 0
While (chunkIndex < chunkCount)
    success = path.SetString(cacheDir)
    success = path.Append("/chunk-")
    success = path.AppendInt(chunkIndex)
    success = data.Clear()
    success = data.LoadFile(path.GetAsString())
    If (success = True) Then
        success = assembled.FileWriteBd(data,0,0)
    End If

    If (success <> True) Then
        assembled.FileClose 
        System.DebugLog("Assembly failed. Verified chunks are retained for resume.")
        Return
    End If

    chunkIndex = chunkIndex + 1
Wend
assembled.FileClose 
Dim assembledSize As String
assembledSize = files.FileSizeStr(assembledPath)
Dim assembledHash As String
assembledHash = crypt.HashFileENC(assembledPath)
If ((crypt.LastMethodSuccess <> True) Or (assembledSize <> expectedSize) Or (assembledHash <> expectedHash)) Then
    System.DebugLog("Assembled archive failed verification; final output was not created.")
    Return
End If

success = files.FileRename(assembledPath,finalPath)
If (success <> True) Then
    System.DebugLog("Verified assembly could not be renamed; keep the cache.")
    Return
End If

System.DebugLog("Archive downloaded and verified. Retained chunks can now be removed manually.")