Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

Amazon Glacier: Resume a Multipart Upload

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.

Verifies the local file against its checkpoint, reads every List Parts page, and compares each exact range and tree hash. Matching parts are skipped; missing or mismatched parts are uploaded. Unexpected server ranges prevent completion. Keep the upload exclusive to this process. A missing upload may be completed, aborted, or expired: do not automatically start over. For an uncertain completion use retry completion.

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 Lua Downloads

Lua
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 state = chilkat.JsonObject.new()
state.strict = true
local saved = chilkat.StringBuilder.new()
success = state:load_file(statePath)
if not success then
    print("Could not load the private multipart checkpoint.")
    return
end

if state:json_type_of("UploadId") ~= 1 then
    print("Missing or invalid UploadId.")
    return
end

if state:string_of("UploadId") == "" then
    print("Empty UploadId.")
    return
end

if state:json_type_of("Region") ~= 1 then
    print("Missing or invalid Region.")
    return
end

if state:string_of("Region") == "" then
    print("Empty Region.")
    return
end

if state:json_type_of("VaultName") ~= 1 then
    print("Missing or invalid VaultName.")
    return
end

if state:string_of("VaultName") == "" then
    print("Empty VaultName.")
    return
end

if state:json_type_of("FilePath") ~= 1 then
    print("Missing or invalid FilePath.")
    return
end

if state:string_of("FilePath") == "" then
    print("Empty FilePath.")
    return
end

if state:json_type_of("ArchiveSize") ~= 1 then
    print("Missing or invalid ArchiveSize.")
    return
end

if state:string_of("ArchiveSize") == "" then
    print("Empty ArchiveSize.")
    return
end

if state:json_type_of("TreeHash") ~= 1 then
    print("Missing or invalid TreeHash.")
    return
end

if state:string_of("TreeHash") == "" then
    print("Empty TreeHash.")
    return
end

if state:json_type_of("PartSize") ~= 1 then
    print("Missing or invalid PartSize.")
    return
end

if state:string_of("PartSize") == "" then
    print("Empty PartSize.")
    return
end

if (state:string_of("Region") ~= region) or (state:string_of("VaultName") ~= "chilkat") then
    print("Checkpoint region/vault differs from this example configuration.")
    return
end

if state:string_of("PartSize") ~= "8388608" then
    print("This workflow requires the original 8 MiB part size.")
    return
end

local uploadId = state:string_of("UploadId")
success = rest:add_path_param("{upload}", uploadId)
if not success then
    print("Could not set upload ID.")
    return
end

if files:file_exists(receiptPath) then
    print("A completion receipt already exists; this upload has finished.")
    return
end

local filePath = state:string_of("FilePath")
local fileSize = files:file_size_str(filePath)
if (not files.last_method_success) or (fileSize ~= state:string_of("ArchiveSize")) then
    print("Local file size differs from the checkpoint.")
    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) or (treeHash ~= state:string_of("TreeHash")) then
    print("Local file checksum differs from the checkpoint; do not resume with a different file.")
    return
end

local remoteParts = chilkat.Hashtable.new()
success = rest:add_query_param("limit", "50")
if not success then
    print("Could not set page limit.")
    return
end

local seenMarkers = chilkat.Hashtable.new()
local marker = ""
local more = true
local page = 0
while more do
    if page == 1000 then
        print("Page limit reached; listing is incomplete.")
        return
    end

    page = page + 1
    if marker ~= "" then
        success = rest:add_query_param("marker", marker)
        if not success then
            print("Could not set marker.")
            return
        end
    end

    success = rest:full_request_no_body_sb("GET", "/-/vaults/{vault}/multipart-uploads/{upload}", 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("MultipartUploadId") ~= 1 then
        print("Missing or invalid MultipartUploadId.")
        return
    end

    if result:string_of("MultipartUploadId") == "" then
        print("Empty MultipartUploadId.")
        return
    end

    if result:json_type_of("PartSizeInBytes") ~= 2 then
        print("Missing or invalid PartSizeInBytes.")
        return
    end

    if (result:string_of("MultipartUploadId") ~= uploadId) or (result:string_of("PartSizeInBytes") ~= state:string_of("PartSize")) then
        print("Server upload identity or part size differs from checkpoint.")
        return
    end

    if result:json_type_of("Parts") ~= 4 then
        print("Missing or invalid Parts.")
        return
    end

    local i = 0
    while i < result:size_of_array("Parts") do
        result.i = i
        if result:json_type_of("Parts[i].RangeInBytes") ~= 1 then
            print("Missing or invalid Parts[i].RangeInBytes.")
            return
        end

        if result:string_of("Parts[i].RangeInBytes") == "" then
            print("Empty Parts[i].RangeInBytes.")
            return
        end

        if result:json_type_of("Parts[i].SHA256TreeHash") ~= 1 then
            print("Missing or invalid Parts[i].SHA256TreeHash.")
            return
        end

        if result:string_of("Parts[i].SHA256TreeHash") == "" then
            print("Empty Parts[i].SHA256TreeHash.")
            return
        end

        local remoteRange = result:string_of("Parts[i].RangeInBytes")
        if remoteParts:contains(remoteRange) then
            print("Duplicate server range; listing is inconsistent.")
            return
        end

        success = remoteParts:add_str(remoteRange, result:string_of("Parts[i].SHA256TreeHash"))
        if not success then
            print("Could not record server part.")
            return
        end

        i = i + 1
    end

    more = false
    if result:json_type_of("Marker") == 1 then
        marker = result:string_of("Marker")
        if marker == "" then
            print("Empty marker; listing is incomplete.")
            return
        end

        if seenMarkers:contains(marker) then
            print("Repeated marker; listing is incomplete.")
            return
        end

        success = seenMarkers:add_str(marker, "seen")
        if not success then
            print("Could not track pagination.")
            return
        end

        more = true
    elseif result:json_type_of("Marker") ~= 6 then
        print("Missing or invalid Marker; listing is incomplete.")
        return
    end
end

success = rest:remove_query_param("limit")
if not success then
    print("Could not clear limit.")
    return
end

if marker ~= "" then
    success = rest:remove_query_param("marker")
    if not success then
        print("Could not clear marker.")
        return
    end
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
local matchedRemoteParts = 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 remoteParts:contains(rangeKey) then
        matchedRemoteParts = matchedRemoteParts + 1
        if remoteParts:lookup_str(rangeKey) == partHash then
            sendPart = false
            print("Verified existing part: " .. rangeKey)
        end
    end

    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()
if matchedRemoteParts ~= remoteParts.count then
    print("Server contains unexpected ranges. Do not complete; inspect the upload and source.")
    files:file_close()
    return
end

-- 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.")