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

B4X
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean = 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 ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/glacier.json")
If success <> True Then
    Log("Could not load private AWS credentials.")
    Return
End If

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

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

'  Set this once to the region containing the vault.
Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("glacier.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "glacier"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("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
        Log("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
            Log("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 ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

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

success = rest.AddHeader("x-amz-glacier-version", "2012-06-01")
If success <> True Then
    Log("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
    Log("Could not set vault name.")
    Return
End If


Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim error As ChilkatJsonObject
error.Initialize
error.Strict = True
Dim responseBody As ChilkatStringBuilder
responseBody.Initialize
Dim jobId As String = "YOUR_JOB_ID"
success = rest.AddPathParam("{job}", jobId)
If success <> True Then
    Log("Could not set job ID.")
    Return
End If

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

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

    End If

    Log("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
    Log("Expected valid JSON response.")
    Return
End If

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

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

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

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

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

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

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

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

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

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

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

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

Dim expectedSize As String = result.StringOf("ArchiveSizeInBytes")
Dim expectedHash As String = result.StringOf("ArchiveSHA256TreeHash")
If result.StringOf("SHA256TreeHash") <> expectedHash Then
    Log("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 Int = 8388608
Dim chunkCount As Int = 0
Dim remainder As Int = 0
Dim position As Int = 0
Dim sizeText As ChilkatStringBuilder
sizeText.Initialize
Dim decimalDigits As ChilkatStringBuilder
decimalDigits.Initialize
Dim digit As ChilkatStringBuilder
digit.Initialize
sizeText.Append(expectedSize)
decimalDigits.Append("0123456789")
If (sizeText.Length = 0) Or (sizeText.Length > 14) Then
    Log("Invalid archive size.")
    Return
End If

Do While (position < sizeText.Length)
    digit.SetString(sizeText.GetRange(position, 1, False))
    If decimalDigits.Contains(digit.GetAsString, True) <> True Then
        Log("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
    Do While (remainder >= chunkSize)
        chunkCount = chunkCount + 1
        remainder = remainder - chunkSize
    Loop
    position = position + 1
Loop
If (chunkCount > 5242880) Or ((chunkCount = 5242880) And (remainder <> 0)) Then
    Log("Archive exceeds the 40 TiB service limit.")
    Return
End If

If (chunkCount = 0) And (remainder = 0) Then
    Log("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 = "qa_output/glacier-download"
Dim finalPath As String = "qa_output/archive-resumed.dat"
Dim files As ChilkatFileAccess
files.Initialize
success = files.DirEnsureExists(cacheDir)
If success <> True Then
    Log("Could not create private download directory.")
    Return
End If

Dim path As ChilkatStringBuilder
path.Initialize
path.Append(cacheDir)
path.Append("/manifest.json")
Dim manifestPath As String = path.GetAsString
Dim manifest As ChilkatJsonObject
manifest.Initialize
manifest.Strict = True
Dim identity As ChilkatJsonObject
identity.Initialize
success = identity.UpdateString("version", "1")
If success <> True Then
    Log("Could not set version.")
    Return
End If

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End If

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

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

Dim rangeHeader As ChilkatStringBuilder
rangeHeader.Initialize
Dim contentRange As ChilkatStringBuilder
contentRange.Initialize
Dim byteCount As ChilkatStringBuilder
byteCount.Initialize
Dim receipt As ChilkatJsonObject
receipt.Initialize
receipt.Strict = True
Dim chunkIndex As Int = 0
Dim byteHigh As Int = 0
Dim byteLow As Int = 0
Dim endHigh As Int
Dim endLow As Int
Dim range As ChilkatStringBuilder
range.Initialize
Dim digits As ChilkatStringBuilder
digits.Initialize
Do While (chunkIndex < chunkCount)
    Dim chunkBytes As Int = chunkSize
    If (chunkIndex = chunkCount - 1) And (remainder <> 0) Then
        chunkBytes = remainder
    End If

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

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

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

    range.Append(digits.GetAsString)
    Dim rangeKey As String = 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)
    Dim chunkPath As String = path.GetAsString
    path.Append(".json")
    Dim receiptPath As String = path.GetAsString
    path.SetString(chunkPath)
    path.Append(".part")
    Dim temporaryPath As String = path.GetAsString
    If files.FileExists(chunkPath) = True Then
        success = receipt.LoadFile(receiptPath)
        If success <> True Then
            Log("Cached chunk lacks a valid receipt. Preserve the cache and inspect it.")
            Return
        End If

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Log("Downloaded verified chunk: " & chunkIndex)
    End If

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

    chunkIndex = chunkIndex + 1
Loop
'  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")
Dim assembledPath As String = path.GetAsString
Dim assembled As ChilkatFileAccess
assembled.Initialize
success = assembled.OpenForWrite(assembledPath)
If success <> True Then
    Log("Could not open assembly file.")
    Return
End If

Dim data As ChilkatBinData
data.Initialize
chunkIndex = 0
Do While (chunkIndex < chunkCount)
    path.SetString(cacheDir)
    path.Append("/chunk-")
    path.AppendInt(chunkIndex)
    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
        Log("Assembly failed. Verified chunks are retained for resume.")
        Return
    End If

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

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

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