Amazon Glacier: Download and Verify Range Retrieval Output
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 the 8 MiB output of the companion range retrieval job. Set its job ID and create qa_output first. DescribeJob must report successful archive retrieval and the expected archive range. The HTTP range bytes=0-8388607 is relative to the job output, although the original archive range starts at 8388608.
Requires HTTP 206, exact Content-Range and Content-Length, the response tree hash, the actual downloaded size, and the job output's SHA256TreeHash before renaming the temporary file. ArchiveSHA256TreeHash hashes the entire original archive and must not be used to validate a partial retrieval. Existing output files are not overwritten. A failed download remains marked .part.
Requires glacier:DescribeJob and glacier:GetJobOutput. Download promptly: job output remains available for at least 24 hours after completion. Both retrieval and download ranges must be tree-hash aligned to receive a checksum. For other range lengths, adjust all expected ranges and lengths together.
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 Xojo Plugin Downloads
// 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.StringOf("RetrievalByteRange") <> "8388608-16777215") Then
System.DebugLog("Use the 8 MiB range job created by the companion example.")
Return
End If
// These offsets are relative to the JOB OUTPUT, not the original archive.
// Output bytes 0..8388607 correspond to archive bytes 8388608..16777215.
Dim expectedHash As String
expectedHash = result.StringOf("SHA256TreeHash")
Dim rangeHeader As New Chilkat.StringBuilder
Dim contentRange As New Chilkat.StringBuilder
Dim byteCount As New Chilkat.StringBuilder
success = rangeHeader.Append("bytes=0-8388607")
success = contentRange.Append("bytes 0-8388607/8388608")
success = byteCount.Append("8388608")
Dim files As New Chilkat.FileAccess
Dim crypt As New Chilkat.Crypt2
crypt.HashAlgorithm = "sha256-tree-hash"
crypt.EncodingMode = "hexlower"
Dim temporaryPath As String
temporaryPath = "qa_output/archive-range.dat.part"
Dim finalPath As String
finalPath = "qa_output/archive-range.dat"
If ((files.FileExists(temporaryPath) = True) Or (files.FileExists(finalPath) = True)) Then
System.DebugLog("Choose unused output paths.")
Return
End If
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
If (actualHash <> expectedHash) Then
System.DebugLog("Range output does not match the retrieval job tree hash.")
Return
End If
success = files.FileRename(temporaryPath,finalPath)
If (success <> True) Then
System.DebugLog("Verified range remains at the temporary path; rename failed.")
Return
End If
System.DebugLog("Archive range downloaded and verified.")