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.
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:json_type_of("ArchiveSizeInBytes") ~= 2 then
print("Missing or invalid ArchiveSizeInBytes.")
return
end
if result:json_type_of("ArchiveId") ~= 1 then
print("Missing or invalid ArchiveId.")
return
end
if result:string_of("ArchiveId") == "" then
print("Empty ArchiveId.")
return
end
if result:json_type_of("ArchiveSHA256TreeHash") ~= 1 then
print("Missing or invalid ArchiveSHA256TreeHash.")
return
end
if result:string_of("ArchiveSHA256TreeHash") == "" then
print("Empty ArchiveSHA256TreeHash.")
return
end
local expectedSize = result:string_of("ArchiveSizeInBytes")
local expectedHash = result:string_of("ArchiveSHA256TreeHash")
if result:string_of("SHA256TreeHash") ~= expectedHash then
print("Use a full-archive retrieval job for this resumable example.")
return
end
-- Fixed 8 MiB chunks are power-of-two and tree-hash aligned.
-- Decimal long division avoids 32-bit overflow in every generated language.
local chunkSize = 8388608
local chunkCount = 0
local remainder = 0
local position = 0
local sizeText = chilkat.StringBuilder.new()
local decimalDigits = chilkat.StringBuilder.new()
local digit = chilkat.StringBuilder.new()
sizeText:append(expectedSize)
decimalDigits:append("0123456789")
if (sizeText.length == 0) or (sizeText.length > 14) then
print("Invalid archive size.")
return
end
while position < sizeText.length do
digit:set_string(sizeText:get_range(position, 1, false))
if not decimalDigits:contains(digit:get_as_string(), true) then
print("Invalid decimal archive size.")
return
end
remainder = remainder * 10 + digit.int_value
-- At most nine subtractions per digit; avoids language-specific division.
chunkCount = chunkCount * 10
while remainder >= chunkSize do
chunkCount = chunkCount + 1
remainder = remainder - chunkSize
end
position = position + 1
end
if (chunkCount > 5242880) or ((chunkCount == 5242880) and (remainder ~= 0)) then
print("Archive exceeds the 40 TiB service limit.")
return
end
if (chunkCount == 0) and (remainder == 0) then
print("Use the single-download example for an empty archive.")
return
end
if remainder ~= 0 then
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.
local cacheDir = "qa_output/glacier-download"
local finalPath = "qa_output/archive-resumed.dat"
local files = chilkat.FileAccess.new()
success = files:dir_ensure_exists(cacheDir)
if not success then
print("Could not create private download directory.")
return
end
local path = chilkat.StringBuilder.new()
path:append(cacheDir)
path:append("/manifest.json")
local manifestPath = path:get_as_string()
local manifest = chilkat.JsonObject.new()
manifest.strict = true
local identity = chilkat.JsonObject.new()
success = identity:update_string("version", "1")
if not success then
print("Could not set version.")
return
end
success = identity:update_string("region", region)
if not success then
print("Could not set region.")
return
end
success = identity:update_string("vault", "chilkat")
if not success then
print("Could not set vault.")
return
end
success = identity:update_string("jobId", jobId)
if not success then
print("Could not set jobId.")
return
end
success = identity:update_string("archiveId", result:string_of("ArchiveId"))
if not success then
print("Could not set archiveId.")
return
end
success = identity:update_string("size", expectedSize)
if not success then
print("Could not set size.")
return
end
success = identity:update_string("treeHash", expectedHash)
if not success then
print("Could not set treeHash.")
return
end
success = identity:update_string("chunkSize", "8388608")
if not success then
print("Could not set chunkSize.")
return
end
success = identity:update_string("finalPath", finalPath)
if not success then
print("Could not set finalPath.")
return
end
if files:file_exists(manifestPath) then
success = manifest:load_file(manifestPath)
if not success then
print("Invalid checkpoint. Preserve the cache and inspect it before restarting.")
return
end
if manifest:string_of("version") ~= identity:string_of("version") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("region") ~= identity:string_of("region") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("vault") ~= identity:string_of("vault") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("jobId") ~= identity:string_of("jobId") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("archiveId") ~= identity:string_of("archiveId") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("size") ~= identity:string_of("size") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("treeHash") ~= identity:string_of("treeHash") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("chunkSize") ~= identity:string_of("chunkSize") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
if manifest:string_of("finalPath") ~= identity:string_of("finalPath") then
print("Checkpoint belongs to different download settings. Use a new empty cache directory.")
return
end
else
local cacheContents = chilkat.DirTree.new()
cacheContents.base_dir = cacheDir
cacheContents.recurse = false
success = cacheContents:begin_iterate()
if (success) or (not cacheContents.done_iterating) then
print("First run requires an empty, readable cache directory.")
return
end
success = identity:write_file(manifestPath)
if not success then
print("Could not save download identity.")
return
end
end
local crypt = chilkat.Crypt2.new()
crypt.hash_algorithm = "sha256-tree-hash"
crypt.encoding_mode = "hexlower"
if files:file_exists(finalPath) then
local finalSize = files:file_size_str(finalPath)
local finalHash = crypt:hash_file_enc(finalPath)
if (not crypt.last_method_success) or ((finalSize ~= expectedSize) or (finalHash ~= expectedHash)) then
print("Existing final file differs; choose another final output path.")
return
end
print("Archive already downloaded and verified.")
return
end
local rangeHeader = chilkat.StringBuilder.new()
local contentRange = chilkat.StringBuilder.new()
local byteCount = chilkat.StringBuilder.new()
local receipt = chilkat.JsonObject.new()
receipt.strict = true
local chunkIndex = 0
local byteHigh = 0
local byteLow = 0
local endHigh = 0
local endLow = 0
local range = chilkat.StringBuilder.new()
local digits = chilkat.StringBuilder.new()
while chunkIndex < chunkCount do
local chunkBytes = chunkSize
if (chunkIndex == chunkCount - 1) and (remainder ~= 0) then
chunkBytes = remainder
end
range:clear()
digits:clear()
digits:append_int(byteLow)
if byteHigh > 0 then
while digits.length < 9 do
digits:prepend("0")
end
range:append_int(byteHigh)
end
range:append(digits:get_as_string())
range:append("-")
endHigh = byteHigh
endLow = byteLow + chunkBytes - 1
if endLow >= 1000000000 then
endLow = endLow - 1000000000
endHigh = endHigh + 1
end
digits:clear()
digits:append_int(endLow)
if endHigh > 0 then
while digits.length < 9 do
digits:prepend("0")
end
range:append_int(endHigh)
end
range:append(digits:get_as_string())
local rangeKey = range:get_as_string()
rangeHeader:set_string("bytes=")
rangeHeader:append(rangeKey)
contentRange:set_string("bytes ")
contentRange:append(rangeKey)
contentRange:append("/")
contentRange:append(expectedSize)
byteCount:clear()
byteCount:append_int(chunkBytes)
path:set_string(cacheDir)
path:append("/chunk-")
path:append_int(chunkIndex)
local chunkPath = path:get_as_string()
path:append(".json")
local receiptPath = path:get_as_string()
path:set_string(chunkPath)
path:append(".part")
local temporaryPath = path:get_as_string()
if files:file_exists(chunkPath) then
success = receipt:load_file(receiptPath)
if not success then
print("Cached chunk lacks a valid receipt. Preserve the cache and inspect it.")
return
end
local cachedHash = crypt:hash_file_enc(chunkPath)
if (not crypt.last_method_success) or ((cachedHash ~= receipt:string_of("treeHash")) or ((receipt:string_of("range") ~= rangeKey) or (files:file_size_str(chunkPath) ~= byteCount:get_as_string()))) then
print("Cached chunk failed verification. Remove only that chunk and its receipt, then rerun.")
return
end
print("Reusing verified chunk: " .. chunkIndex)
else
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
success = receipt:update_string("range", rangeKey)
if not success then
print("Could not set range.")
return
end
success = receipt:update_string("treeHash", actualHash)
if not success then
print("Could not set treeHash.")
return
end
success = receipt:write_file(receiptPath)
if not success then
print("Could not save chunk checksum; temporary bytes remain uncommitted.")
return
end
success = files:file_rename(temporaryPath, chunkPath)
if not success then
print("Could not commit verified chunk.")
return
end
print("Downloaded verified chunk: " .. chunkIndex)
end
byteHigh = endHigh
byteLow = endLow + 1
if byteLow == 1000000000 then
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:set_string(cacheDir)
path:append("/assembled.part")
local assembledPath = path:get_as_string()
local assembled = chilkat.FileAccess.new()
success = assembled:open_for_write(assembledPath)
if not success then
print("Could not open assembly file.")
return
end
local data = chilkat.BinData.new()
chunkIndex = 0
while chunkIndex < chunkCount do
path:set_string(cacheDir)
path:append("/chunk-")
path:append_int(chunkIndex)
data:clear()
success = data:load_file(path:get_as_string())
if success then
success = assembled:file_write_bd(data, 0, 0)
end
if not success then
assembled:file_close()
print("Assembly failed. Verified chunks are retained for resume.")
return
end
chunkIndex = chunkIndex + 1
end
assembled:file_close()
local assembledSize = files:file_size_str(assembledPath)
local assembledHash = crypt:hash_file_enc(assembledPath)
if (not crypt.last_method_success) or ((assembledSize ~= expectedSize) or (assembledHash ~= expectedHash)) then
print("Assembled archive failed verification; final output was not created.")
return
end
success = files:file_rename(assembledPath, finalPath)
if not success then
print("Verified assembly could not be renamed; keep the cache.")
return
end
print("Archive downloaded and verified. Retained chunks can now be removed manually.")