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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Private configuration, not a file in public web content or source control.
-- Load current IAM credentials authorized for the Glacier operation.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/glacier.json")
if not success then
print("Could not load private AWS credentials.")
return
end
if (credentials:json_type_of("access_key") ~= 1) or (credentials:string_of("access_key") == "") then
print("Missing or invalid access_key.")
return
end
if (credentials:json_type_of("secret_key") ~= 1) or (credentials:string_of("secret_key") == "") then
print("Missing or invalid secret_key.")
return
end
-- Set this once to the region containing the vault.
local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("glacier.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "glacier"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
success = rest:set_auth_aws(aws)
if not success then
print("Could not configure AWS signing.")
return
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:has_member("session_token") then
if credentials:json_type_of("session_token") ~= 1 then
print("session_token must be a string.")
return
end
if credentials:string_of("session_token") ~= "" then
success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
if not success then
print("Could not set the session-token parameter.")
return
end
end
end
-- Supply a Socket to explicitly enable TLS certificate verification.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS connection failed; inspect diagnostics privately.")
return
end
success = rest:use_connection(connection, true)
if not success then
print("Could not attach the TLS connection.")
return
end
success = rest:add_header("x-amz-glacier-version", "2012-06-01")
if not success then
print("Could not set x-amz-glacier-version.")
return
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:add_path_param("{vault}", "chilkat")
if not success then
print("Could not set vault name.")
return
end
local result = chilkat.JsonObject.new()
result.strict = true
local error_ = chilkat.JsonObject.new()
error_.strict = true
local responseBody = chilkat.StringBuilder.new()
local jobId = "YOUR_JOB_ID"
success = rest:add_path_param("{job}", jobId)
if not success then
print("Could not set job ID.")
return
end
success = rest:full_request_no_body_sb("GET", "/-/vaults/{vault}/jobs/{job}", responseBody)
if not success then
print("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
return
end
if rest.response_status_code ~= 200 then
print("Glacier HTTP status: " .. rest.response_status_code)
success = error_:load_sb(responseBody)
if success then
if error_:json_type_of("code") == 1 then
print("AWS error code: " .. error_:string_of("code"))
end
end
print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
-- Inspect full errors privately. An HTTP error is not a successful operation.
return
end
success = result:load_sb(responseBody)
if not success then
print("Expected valid JSON response.")
return
end
if result:json_type_of("Completed") ~= 5 then
print("Missing or invalid Completed.")
return
end
if result:json_type_of("StatusCode") ~= 1 then
print("Missing or invalid StatusCode.")
return
end
if result:string_of("StatusCode") == "" then
print("Empty StatusCode.")
return
end
if (not result:bool_of("Completed")) or (result:string_of("StatusCode") ~= "Succeeded") then
print("Job is not successfully complete. Resume later only if InProgress.")
return
end
if result:string_of("Action") ~= "ArchiveRetrieval" then
print("Wrong job type.")
return
end
if result:json_type_of("SHA256TreeHash") ~= 1 then
print("Missing or invalid SHA256TreeHash.")
return
end
if result:string_of("SHA256TreeHash") == "" then
print("Empty SHA256TreeHash.")
return
end
if result:string_of("RetrievalByteRange") ~= "8388608-16777215" then
print("Use the 8 MiB range job created by the companion example.")
return
end
-- These offsets are relative to the JOB OUTPUT, not the original archive.
-- Output bytes 0..8388607 correspond to archive bytes 8388608..16777215.
local expectedHash = result:string_of("SHA256TreeHash")
local rangeHeader = chilkat.StringBuilder.new()
local contentRange = chilkat.StringBuilder.new()
local byteCount = chilkat.StringBuilder.new()
rangeHeader:append("bytes=0-8388607")
contentRange:append("bytes 0-8388607/8388608")
byteCount:append("8388608")
local files = chilkat.FileAccess.new()
local crypt = chilkat.Crypt2.new()
crypt.hash_algorithm = "sha256-tree-hash"
crypt.encoding_mode = "hexlower"
local temporaryPath = "qa_output/archive-range.dat.part"
local finalPath = "qa_output/archive-range.dat"
if (files:file_exists(temporaryPath)) or (files:file_exists(finalPath)) then
print("Choose unused output paths.")
return
end
success = rest:add_header("Range", rangeHeader:get_as_string())
if not success then
print("Could not set Range.")
return
end
success = rest:send_req_no_body("GET", "/-/vaults/{vault}/jobs/{job}/output")
if not success then
print("Could not send range request. Rerun to resume.")
return
end
local httpStatus = rest:read_response_header()
if httpStatus ~= 206 then
print("Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.")
return
end
local responseRange = rest:response_hdr_by_name("Content-Range")
if (not rest.last_method_success) or (responseRange ~= contentRange:get_as_string()) then
print("Unexpected Content-Range; refusing download.")
return
end
local responseLength = rest:response_hdr_by_name("Content-Length")
if (not rest.last_method_success) or (responseLength ~= byteCount:get_as_string()) then
print("Unexpected Content-Length; refusing download.")
return
end
local responseHash = rest:response_hdr_by_name("x-amz-sha256-tree-hash")
if (not rest.last_method_success) or (responseHash == "") then
print("Missing range tree hash. Require a tree-hash-aligned retrieval and download range.")
return
end
local output = chilkat.Stream.new()
output.sink_file = temporaryPath
success = rest:read_resp_body_stream(output, true)
if not success then
print("Download interrupted; rerun to resume. Temporary bytes are not trusted.")
return
end
local actualSize = files:file_size_str(temporaryPath)
if (not files.last_method_success) or (actualSize ~= byteCount:get_as_string()) then
print("Downloaded size mismatch.")
return
end
local actualHash = crypt:hash_file_enc(temporaryPath)
if (not crypt.last_method_success) or (actualHash ~= responseHash) then
print("Downloaded tree hash mismatch.")
return
end
if actualHash ~= expectedHash then
print("Range output does not match the retrieval job tree hash.")
return
end
success = files:file_rename(temporaryPath, finalPath)
if not success then
print("Verified range remains at the temporary path; rename failed.")
return
end
print("Archive range downloaded and verified.")