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

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.

AWS reference

Chilkat Xojo Plugin Downloads

Xojo Plugin
//  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 body As New Chilkat.JsonObject
Dim result As New Chilkat.JsonObject
result.Strict = True
Dim error As New Chilkat.JsonObject
error.Strict = True
Dim requestBody As New Chilkat.StringBuilder
Dim responseBody As New Chilkat.StringBuilder
Dim files As New Chilkat.FileAccess
Dim statePath As String
statePath = "qa_output/glacier-multipart.json"
Dim receiptPath As String
receiptPath = "qa_output/glacier-multipart-completed.json"
Dim tempPath As String
tempPath = "qa_output/glacier-multipart.json.tmp"
Dim state As New Chilkat.JsonObject
state.Strict = True
Dim saved As New Chilkat.StringBuilder
If ((files.FileExists(statePath) = True) Or (files.FileExists(tempPath) = True) Or (files.FileExists(receiptPath) = True)) Then
    System.DebugLog("Existing checkpoint/receipt found. Resume or inspect it; choose new paths for a new archive.")
    Return
End If

Dim filePath As String
filePath = "qa_data/zips/somethingBig.zip"
Dim fileSize As String
fileSize = files.FileSizeStr(filePath)
If ((files.LastMethodSuccess <> True) Or (fileSize = "0")) Then
    System.DebugLog("Source file must exist and be nonempty.")
    Return
End If

success = files.OpenForRead(filePath)
If (success <> True) Then
    System.DebugLog("Could not open source.")
    Return
End If

Dim initialParts As Int32
initialParts = files.GetNumBlocks(8388608)
files.FileClose 
If ((initialParts < 1) Or (initialParts > 10000)) Then
    System.DebugLog("Source exceeds the 10,000-part limit for this 8 MiB example.")
    Return
End If

Dim crypt As New Chilkat.Crypt2
crypt.HashAlgorithm = "sha256-tree-hash"
crypt.EncodingMode = "hexlower"
Dim treeHash As String
treeHash = crypt.HashFileENC(filePath)
If (crypt.LastMethodSuccess <> True) Then
    System.DebugLog("Could not hash source file.")
    Return
End If

success = state.UpdateString("Region",region)
If (success <> True) Then
    System.DebugLog("Could not set Region.")
    Return
End If

success = state.UpdateString("VaultName","chilkat")
If (success <> True) Then
    System.DebugLog("Could not set VaultName.")
    Return
End If

success = state.UpdateString("FilePath",filePath)
If (success <> True) Then
    System.DebugLog("Could not set FilePath.")
    Return
End If

success = state.UpdateString("ArchiveSize",fileSize)
If (success <> True) Then
    System.DebugLog("Could not set ArchiveSize.")
    Return
End If

success = state.UpdateString("TreeHash",treeHash)
If (success <> True) Then
    System.DebugLog("Could not set TreeHash.")
    Return
End If

success = state.UpdateString("PartSize","8388608")
If (success <> True) Then
    System.DebugLog("Could not set PartSize.")
    Return
End If

saved.Clear 
success = state.EmitSb(saved)
If (success <> True) Then
    System.DebugLog("Could not serialize pending checkpoint.")
    Return
End If

success = saved.WriteFile(tempPath,"utf-8",False)
If (success <> True) Then
    System.DebugLog("Cannot write checkpoint; no upload was initiated.")
    Return
End If

success = rest.AddHeader("x-amz-part-size","8388608")
If (success <> True) Then
    System.DebugLog("Could not set x-amz-part-size.")
    Return
End If

success = rest.AddHeader("x-amz-archive-description","Multipart archive example")
If (success <> True) Then
    System.DebugLog("Could not set x-amz-archive-description.")
    Return
End If

success = rest.FullRequestNoBodySb("POST","/-/vaults/{vault}/multipart-uploads",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 <> 201) 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

Dim uploadId As String
uploadId = rest.ResponseHdrByName("x-amz-multipart-upload-id")
If ((rest.LastMethodSuccess <> True) Or (uploadId = "")) Then
    System.DebugLog("Missing upload ID. Inspect multipart uploads before initiating another upload.")
    Return
End If

System.DebugLog("Upload ID (preserve this): " + uploadId)
success = state.UpdateString("UploadId",uploadId)
If (success <> True) Then
    System.DebugLog("Could not set UploadId.")
    Return
End If

saved.Clear 
success = state.EmitSb(saved)
If (success <> True) Then
    System.DebugLog("Could not serialize checkpoint; preserve the printed upload ID.")
    Return
End If

success = saved.WriteFile(tempPath,"utf-8",False)
If (success <> True) Then
    System.DebugLog("Could not persist upload ID; preserve it and stop.")
    Return
End If

success = files.FileRename(tempPath,statePath)
If (success <> True) Then
    System.DebugLog("Checkpoint remains in .tmp; recover it before resuming.")
    Return
End If

success = rest.AddPathParam("{upload}",uploadId)
If (success <> True) Then
    System.DebugLog("Could not set upload ID.")
    Return
End If

success = rest.RemoveHeader("x-amz-part-size")
If (success <> True) Then
    System.DebugLog("Could not clear initiation header.")
    Return
End If

success = rest.RemoveHeader("x-amz-archive-description")
If (success <> True) Then
    System.DebugLog("Could not clear description header.")
    Return
End If

success = files.OpenForRead(filePath)
If (success <> True) Then
    System.DebugLog("Could not open the immutable source file.")
    files.FileClose 
    Return
End If

Dim partSize As Int32
partSize = 8388608
Dim numParts As Int32
numParts = files.GetNumBlocks(partSize)
If ((numParts < 1) Or (numParts > 10000)) Then
    System.DebugLog("This 8 MiB example supports nonempty files of at most 10,000 parts.")
    files.FileClose 
    Return
End If

//  Two base-1,000,000,000 components avoid 32-bit overflow in COM languages.
Dim byteHigh As Int32
byteHigh = 0
Dim byteLow As Int32
byteLow = 0
Dim endHigh As Int32
Dim endLow As Int32
Dim range As New Chilkat.StringBuilder
Dim digits As New Chilkat.StringBuilder
Dim part As New Chilkat.BinData
Dim partIndex As Int32
partIndex = 0
While (partIndex < numParts)
    success = part.Clear()
    If (success <> True) Then
        System.DebugLog("Could not clear part buffer.")
        files.FileClose 
        Return
    End If

    success = files.ReadBlockBd(partIndex,partSize,part)
    If (success <> True) Then
        System.DebugLog("Could not read the source part.")
        files.FileClose 
        Return
    End If

    If ((part.NumBytes = 0) Or ((partIndex < numParts - 1) And (part.NumBytes <> partSize))) Then
        System.DebugLog("Source file changed or a part was read incompletely.")
        files.FileClose 
        Return
    End If

    range.Clear 
    digits.Clear 
    success = digits.AppendInt(byteLow)
    If (byteHigh > 0) Then
        While (digits.Length < 9)
            success = digits.Prepend("0")
        Wend
        success = range.AppendInt(byteHigh)
    End If

    success = range.Append(digits.GetAsString())
    success = range.Append("-")
    endHigh = byteHigh
    endLow = byteLow + part.NumBytes - 1
    If (endLow >= 1000000000) Then
        endLow = endLow - 1000000000
        endHigh = endHigh + 1
    End If

    digits.Clear 
    success = digits.AppendInt(endLow)
    If (endHigh > 0) Then
        While (digits.Length < 9)
            success = digits.Prepend("0")
        Wend
        success = range.AppendInt(endHigh)
    End If

    success = range.Append(digits.GetAsString())
    Dim rangeKey As String
    rangeKey = range.GetAsString()
    crypt.HashAlgorithm = "sha256-tree-hash"
    Dim partHash As String
    partHash = crypt.HashBdENC(part)
    If (crypt.LastMethodSuccess <> True) Then
        System.DebugLog("Could not hash source part.")
        files.FileClose 
        Return
    End If

    Dim sendPart As Boolean
    sendPart = True
    If (sendPart = True) Then
        crypt.HashAlgorithm = "sha256"
        Dim linearHash As String
        linearHash = crypt.HashBdENC(part)
        If (crypt.LastMethodSuccess <> True) Then
            System.DebugLog("Could not hash the part payload.")
            files.FileClose 
            Return
        End If

        aws.PrecomputedSha256 = linearHash
        success = rest.SetAuthAws(aws)
        If (success <> True) Then
            System.DebugLog("Could not configure part signing.")
            files.FileClose 
            Return
        End If

        success = rest.AddHeader("x-amz-content-sha256",linearHash)
        If (success <> True) Then
            System.DebugLog("Could not set x-amz-content-sha256.")
            files.FileClose 
            Return
        End If

        success = rest.AddHeader("x-amz-sha256-tree-hash",partHash)
        If (success <> True) Then
            System.DebugLog("Could not set x-amz-sha256-tree-hash.")
            files.FileClose 
            Return
        End If

        success = range.Prepend("bytes ")
        success = range.Append("/*")
        success = rest.AddHeader("Content-Range",range.GetAsString())
        If (success <> True) Then
            System.DebugLog("Could not set Content-Range.")
            files.FileClose 
            Return
        End If

        success = rest.AddHeader("Content-Type","application/octet-stream")
        If (success <> True) Then
            System.DebugLog("Could not set Content-Type.")
            files.FileClose 
            Return
        End If

        success = rest.FullRequestBd("PUT","/-/vaults/{vault}/multipart-uploads/{upload}",part,responseBody)
        If (success <> True) Then
            System.DebugLog("Part request did not complete. Keep the checkpoint and run the resume example.")
            files.FileClose 
            Return
        End If

        If (rest.ResponseStatusCode <> 204) 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.
            files.FileClose 
            Return
        End If

        Dim confirmedHash As String
        confirmedHash = rest.ResponseHdrByName("x-amz-sha256-tree-hash")
        If (confirmedHash <> partHash) Then
            System.DebugLog("Part response checksum mismatch. Keep the checkpoint and inspect List Parts.")
            files.FileClose 
            Return
        End If

        System.DebugLog("Uploaded part: " + rangeKey)
    End If

    byteLow = byteLow + part.NumBytes
    If (byteLow >= 1000000000) Then
        byteLow = byteLow - 1000000000
        byteHigh = byteHigh + 1
    End If

    partIndex = partIndex + 1
Wend
files.FileClose 
//  Recheck the source before completion. Keep the file immutable throughout.
fileSize = files.FileSizeStr(filePath)
If ((files.LastMethodSuccess <> True) Or (fileSize <> state.StringOf("ArchiveSize"))) Then
    System.DebugLog("Source size changed during upload; do not complete.")
    files.FileClose 
    Return
End If

crypt.HashAlgorithm = "sha256-tree-hash"
treeHash = crypt.HashFileENC(filePath)
If ((crypt.LastMethodSuccess <> True) Or (treeHash <> state.StringOf("TreeHash"))) Then
    System.DebugLog("Source checksum changed during upload; do not complete.")
    files.FileClose 
    Return
End If

success = rest.AddHeader("x-amz-sha256-tree-hash",state.StringOf("TreeHash"))
If (success <> True) Then
    System.DebugLog("Could not set x-amz-sha256-tree-hash.")
    files.FileClose 
    Return
End If

success = rest.AddHeader("x-amz-archive-size",state.StringOf("ArchiveSize"))
If (success <> True) Then
    System.DebugLog("Could not set x-amz-archive-size.")
    files.FileClose 
    Return
End If

//  Completion has NO body: never reuse a part's precomputed payload hash.
aws.PrecomputedSha256 = ""
success = rest.SetAuthAws(aws)
If (success <> True) Then
    System.DebugLog("Could not reset signing.")
    files.FileClose 
    Return
End If

success = rest.RemoveHeader("x-amz-content-sha256")
If (success <> True) Then
    System.DebugLog("Could not clear part payload hash.")
    files.FileClose 
    Return
End If

success = rest.RemoveHeader("Content-Range")
If (success <> True) Then
    System.DebugLog("Could not clear part range.")
    files.FileClose 
    Return
End If

success = rest.RemoveHeader("Content-Type")
If (success <> True) Then
    System.DebugLog("Could not clear content type.")
    files.FileClose 
    Return
End If

success = rest.FullRequestNoBodySb("POST","/-/vaults/{vault}/multipart-uploads/{upload}",responseBody)
If (success <> True) Then
    System.DebugLog("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
    files.FileClose 
    Return
End If

If (rest.ResponseStatusCode <> 201) 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.
    files.FileClose 
    Return
End If

Dim archiveId As String
archiveId = rest.ResponseHdrByName("x-amz-archive-id")
If ((rest.LastMethodSuccess <> True) Or (archiveId = "")) Then
    System.DebugLog("Completion response has no archive ID. Preserve the checkpoint and retry identical completion promptly.")
    files.FileClose 
    Return
End If

System.DebugLog("Archive ID: " + archiveId)
Dim location As String
location = rest.ResponseHdrByName("Location")
System.DebugLog("Location: " + location)
Dim returnedHash As String
returnedHash = rest.ResponseHdrByName("x-amz-sha256-tree-hash")
If ((rest.LastMethodSuccess = True) And (returnedHash <> state.StringOf("TreeHash"))) Then
    System.DebugLog("Completion checksum mismatch; preserve the printed archive ID and investigate.")
    files.FileClose 
    Return
End If

Dim receipt As New Chilkat.JsonObject
success = receipt.UpdateString("UploadId",uploadId)
If (success <> True) Then
    System.DebugLog("Could not set UploadId.")
    files.FileClose 
    Return
End If

success = receipt.UpdateString("ArchiveId",archiveId)
If (success <> True) Then
    System.DebugLog("Could not set ArchiveId.")
    files.FileClose 
    Return
End If

success = receipt.UpdateString("Location",location)
If (success <> True) Then
    System.DebugLog("Could not set Location.")
    files.FileClose 
    Return
End If

success = receipt.UpdateString("TreeHash",state.StringOf("TreeHash"))
If (success <> True) Then
    System.DebugLog("Could not set TreeHash.")
    files.FileClose 
    Return
End If

saved.Clear 
success = receipt.EmitSb(saved)
If (success <> True) Then
    System.DebugLog("Could not serialize receipt; preserve the printed archive ID.")
    files.FileClose 
    Return
End If

success = saved.WriteFile(receiptPath,"utf-8",False)
If (success <> True) Then
    System.DebugLog("Could not save receipt; preserve the printed archive ID.")
    files.FileClose 
    Return
End If

System.DebugLog("Completion receipt saved. Keep it in your archive catalog.")