Amazon Glacier: Upload an Archive in Parts
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.
Uses fixed 8 MiB parts, at most 10,000 parts (78.125 GiB), and buffers one part at a time. The API also allows other power-of-two MiB sizes up to 4 GiB; this portable example deliberately fixes the size. The last part may be smaller. Use a nonempty, immutable file and one writer per upload. Create qa_output first. Byte offsets and archive sizes stay exact in languages with 32-bit integers.
The private checkpoint stores the upload ID, region, vault, file path, size, part size, and full-file tree hash. Preserve it across failures. It contains no AWS credentials. A separate completion receipt records the archive ID. A lost initiation response requires inspecting List Multipart Uploads; starting a new upload is not a retry of the old one. Inactive uploads can expire after 24 hours. Do not abort automatically on transient errors.
Initiates the upload, saves its ID before sending data, uploads each range with both checksums, and completes with the tree hash of the entire file. Part hashes are not concatenated as hexadecimal strings. Link: resume an interrupted upload.
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 body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
local error_ = chilkat.JsonObject.new()
error_.strict = true
local requestBody = chilkat.StringBuilder.new()
local responseBody = chilkat.StringBuilder.new()
local files = chilkat.FileAccess.new()
local statePath = "qa_output/glacier-multipart.json"
local receiptPath = "qa_output/glacier-multipart-completed.json"
local tempPath = "qa_output/glacier-multipart.json.tmp"
local state = chilkat.JsonObject.new()
state.strict = true
local saved = chilkat.StringBuilder.new()
if (files:file_exists(statePath)) or ((files:file_exists(tempPath)) or (files:file_exists(receiptPath))) then
print("Existing checkpoint/receipt found. Resume or inspect it; choose new paths for a new archive.")
return
end
local filePath = "qa_data/zips/somethingBig.zip"
local fileSize = files:file_size_str(filePath)
if (not files.last_method_success) or (fileSize == "0") then
print("Source file must exist and be nonempty.")
return
end
success = files:open_for_read(filePath)
if not success then
print("Could not open source.")
return
end
local initialParts = files:get_num_blocks(8388608)
files:file_close()
if (initialParts < 1) or (initialParts > 10000) then
print("Source exceeds the 10,000-part limit for this 8 MiB example.")
return
end
local crypt = chilkat.Crypt2.new()
crypt.hash_algorithm = "sha256-tree-hash"
crypt.encoding_mode = "hexlower"
local treeHash = crypt:hash_file_enc(filePath)
if not crypt.last_method_success then
print("Could not hash source file.")
return
end
success = state:update_string("Region", region)
if not success then
print("Could not set Region.")
return
end
success = state:update_string("VaultName", "chilkat")
if not success then
print("Could not set VaultName.")
return
end
success = state:update_string("FilePath", filePath)
if not success then
print("Could not set FilePath.")
return
end
success = state:update_string("ArchiveSize", fileSize)
if not success then
print("Could not set ArchiveSize.")
return
end
success = state:update_string("TreeHash", treeHash)
if not success then
print("Could not set TreeHash.")
return
end
success = state:update_string("PartSize", "8388608")
if not success then
print("Could not set PartSize.")
return
end
saved:clear()
success = state:emit_sb(saved)
if not success then
print("Could not serialize pending checkpoint.")
return
end
success = saved:write_file(tempPath, "utf-8", false)
if not success then
print("Cannot write checkpoint; no upload was initiated.")
return
end
success = rest:add_header("x-amz-part-size", "8388608")
if not success then
print("Could not set x-amz-part-size.")
return
end
success = rest:add_header("x-amz-archive-description", "Multipart archive example")
if not success then
print("Could not set x-amz-archive-description.")
return
end
success = rest:full_request_no_body_sb("POST", "/-/vaults/{vault}/multipart-uploads", 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 ~= 201 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
local uploadId = rest:response_hdr_by_name("x-amz-multipart-upload-id")
if (not rest.last_method_success) or (uploadId == "") then
print("Missing upload ID. Inspect multipart uploads before initiating another upload.")
return
end
print("Upload ID (preserve this): " .. uploadId)
success = state:update_string("UploadId", uploadId)
if not success then
print("Could not set UploadId.")
return
end
saved:clear()
success = state:emit_sb(saved)
if not success then
print("Could not serialize checkpoint; preserve the printed upload ID.")
return
end
success = saved:write_file(tempPath, "utf-8", false)
if not success then
print("Could not persist upload ID; preserve it and stop.")
return
end
success = files:file_rename(tempPath, statePath)
if not success then
print("Checkpoint remains in .tmp; recover it before resuming.")
return
end
success = rest:add_path_param("{upload}", uploadId)
if not success then
print("Could not set upload ID.")
return
end
success = rest:remove_header("x-amz-part-size")
if not success then
print("Could not clear initiation header.")
return
end
success = rest:remove_header("x-amz-archive-description")
if not success then
print("Could not clear description header.")
return
end
success = files:open_for_read(filePath)
if not success then
print("Could not open the immutable source file.")
files:file_close()
return
end
local partSize = 8388608
local numParts = files:get_num_blocks(partSize)
if (numParts < 1) or (numParts > 10000) then
print("This 8 MiB example supports nonempty files of at most 10,000 parts.")
files:file_close()
return
end
-- Two base-1,000,000,000 components avoid 32-bit overflow in COM languages.
local byteHigh = 0
local byteLow = 0
local endHigh = 0
local endLow = 0
local range = chilkat.StringBuilder.new()
local digits = chilkat.StringBuilder.new()
local part = chilkat.BinData.new()
local partIndex = 0
while partIndex < numParts do
success = part:clear()
if not success then
print("Could not clear part buffer.")
files:file_close()
return
end
success = files:read_block_bd(partIndex, partSize, part)
if not success then
print("Could not read the source part.")
files:file_close()
return
end
if (part.num_bytes == 0) or ((partIndex < numParts - 1) and (part.num_bytes ~= partSize)) then
print("Source file changed or a part was read incompletely.")
files:file_close()
return
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 + part.num_bytes - 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()
crypt.hash_algorithm = "sha256-tree-hash"
local partHash = crypt:hash_bd_enc(part)
if not crypt.last_method_success then
print("Could not hash source part.")
files:file_close()
return
end
local sendPart = true
if sendPart then
crypt.hash_algorithm = "sha256"
local linearHash = crypt:hash_bd_enc(part)
if not crypt.last_method_success then
print("Could not hash the part payload.")
files:file_close()
return
end
aws.precomputed_sha256 = linearHash
success = rest:set_auth_aws(aws)
if not success then
print("Could not configure part signing.")
files:file_close()
return
end
success = rest:add_header("x-amz-content-sha256", linearHash)
if not success then
print("Could not set x-amz-content-sha256.")
files:file_close()
return
end
success = rest:add_header("x-amz-sha256-tree-hash", partHash)
if not success then
print("Could not set x-amz-sha256-tree-hash.")
files:file_close()
return
end
range:prepend("bytes ")
range:append("/*")
success = rest:add_header("Content-Range", range:get_as_string())
if not success then
print("Could not set Content-Range.")
files:file_close()
return
end
success = rest:add_header("Content-Type", "application/octet-stream")
if not success then
print("Could not set Content-Type.")
files:file_close()
return
end
success = rest:full_request_bd("PUT", "/-/vaults/{vault}/multipart-uploads/{upload}", part, responseBody)
if not success then
print("Part request did not complete. Keep the checkpoint and run the resume example.")
files:file_close()
return
end
if rest.response_status_code ~= 204 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.
files:file_close()
return
end
local confirmedHash = rest:response_hdr_by_name("x-amz-sha256-tree-hash")
if confirmedHash ~= partHash then
print("Part response checksum mismatch. Keep the checkpoint and inspect List Parts.")
files:file_close()
return
end
print("Uploaded part: " .. rangeKey)
end
byteLow = byteLow + part.num_bytes
if byteLow >= 1000000000 then
byteLow = byteLow - 1000000000
byteHigh = byteHigh + 1
end
partIndex = partIndex + 1
end
files:file_close()
-- Recheck the source before completion. Keep the file immutable throughout.
fileSize = files:file_size_str(filePath)
if (not files.last_method_success) or (fileSize ~= state:string_of("ArchiveSize")) then
print("Source size changed during upload; do not complete.")
files:file_close()
return
end
crypt.hash_algorithm = "sha256-tree-hash"
treeHash = crypt:hash_file_enc(filePath)
if (not crypt.last_method_success) or (treeHash ~= state:string_of("TreeHash")) then
print("Source checksum changed during upload; do not complete.")
files:file_close()
return
end
success = rest:add_header("x-amz-sha256-tree-hash", state:string_of("TreeHash"))
if not success then
print("Could not set x-amz-sha256-tree-hash.")
files:file_close()
return
end
success = rest:add_header("x-amz-archive-size", state:string_of("ArchiveSize"))
if not success then
print("Could not set x-amz-archive-size.")
files:file_close()
return
end
-- Completion has NO body: never reuse a part's precomputed payload hash.
aws.precomputed_sha256 = ""
success = rest:set_auth_aws(aws)
if not success then
print("Could not reset signing.")
files:file_close()
return
end
success = rest:remove_header("x-amz-content-sha256")
if not success then
print("Could not clear part payload hash.")
files:file_close()
return
end
success = rest:remove_header("Content-Range")
if not success then
print("Could not clear part range.")
files:file_close()
return
end
success = rest:remove_header("Content-Type")
if not success then
print("Could not clear content type.")
files:file_close()
return
end
success = rest:full_request_no_body_sb("POST", "/-/vaults/{vault}/multipart-uploads/{upload}", responseBody)
if not success then
print("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
files:file_close()
return
end
if rest.response_status_code ~= 201 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.
files:file_close()
return
end
local archiveId = rest:response_hdr_by_name("x-amz-archive-id")
if (not rest.last_method_success) or (archiveId == "") then
print("Completion response has no archive ID. Preserve the checkpoint and retry identical completion promptly.")
files:file_close()
return
end
print("Archive ID: " .. archiveId)
local location = rest:response_hdr_by_name("Location")
print("Location: " .. location)
local returnedHash = rest:response_hdr_by_name("x-amz-sha256-tree-hash")
if (rest.last_method_success) and (returnedHash ~= state:string_of("TreeHash")) then
print("Completion checksum mismatch; preserve the printed archive ID and investigate.")
files:file_close()
return
end
local receipt = chilkat.JsonObject.new()
success = receipt:update_string("UploadId", uploadId)
if not success then
print("Could not set UploadId.")
files:file_close()
return
end
success = receipt:update_string("ArchiveId", archiveId)
if not success then
print("Could not set ArchiveId.")
files:file_close()
return
end
success = receipt:update_string("Location", location)
if not success then
print("Could not set Location.")
files:file_close()
return
end
success = receipt:update_string("TreeHash", state:string_of("TreeHash"))
if not success then
print("Could not set TreeHash.")
files:file_close()
return
end
saved:clear()
success = receipt:emit_sb(saved)
if not success then
print("Could not serialize receipt; preserve the printed archive ID.")
files:file_close()
return
end
success = saved:write_file(receiptPath, "utf-8", false)
if not success then
print("Could not save receipt; preserve the printed archive ID.")
files:file_close()
return
end
print("Completion receipt saved. Keep it in your archive catalog.")