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

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.

AWS reference

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoCredentials
    String sRegion
    Handle hoEndpoint
    Variant vAws
    Handle hoAws
    Handle hoRest
    Variant vConnection
    Handle hoConnection
    Handle hoResult
    Handle hoError
    Variant vResponseBody
    Handle hoResponseBody
    String sJobId
    String sExpectedHash
    Handle hoRangeHeader
    Handle hoContentRange
    Handle hoByteCount
    Handle hoFiles
    Handle hoCrypt
    String sTemporaryPath
    String sFinalPath
    Integer iHttpStatus
    String sResponseRange
    String sResponseLength
    String sResponseHash
    Variant vOutput
    Handle hoOutput
    String sActualSize
    String sActualHash
    String sTemp1
    Integer iTemp1
    Boolean bTemp1
    Boolean bTemp2

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the Glacier operation.
    Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
    If (Not(IsComObjectCreated(hoCredentials))) Begin
        Send CreateComObject of hoCredentials
    End
    Set ComStrict Of hoCredentials To True
    Get ComLoadFile Of hoCredentials "qa_data/aws/glacier.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load private AWS credentials."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid access_key."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid secret_key."
        Procedure_Return
    End

    //  Set this once to the region containing the vault.
    Move "us-west-2" To sRegion
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "glacier." To iSuccess
    Get ComAppend Of hoEndpoint sRegion To iSuccess
    Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
    Get Create (RefClass(cComChilkatAuthAws)) To hoAws
    If (Not(IsComObjectCreated(hoAws))) Begin
        Send CreateComObject of hoAws
    End
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    Set ComAccessKey Of hoAws To sTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Set ComSecretKey Of hoAws To sTemp1
    Set ComRegion Of hoAws To sRegion
    Set ComServiceName Of hoAws To "glacier"
    Set ComSignatureVersion Of hoAws To 4
    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Set ComConnectTimeoutMs Of hoRest To 20000
    Set ComIdleTimeoutMs Of hoRest To 60000
    Get pvComObject of hoAws to vAws
    Get ComSetAuthAws Of hoRest vAws To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure AWS signing."
        Procedure_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.
    Get ComHasMember Of hoCredentials "session_token" To bTemp1
    If (bTemp1 = True) Begin
        Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
        If (iTemp1 <> 1) Begin
            Showln "session_token must be a string."
            Procedure_Return
        End

        Get ComStringOf Of hoCredentials "session_token" To sTemp1
        If (sTemp1 <> "") Begin
            Get ComStringOf Of hoCredentials "session_token" To sTemp1
            Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set the session-token parameter."
                Procedure_Return
            End

        End

    End

    //  Supply a Socket to explicitly enable TLS certificate verification.
    Get Create (RefClass(cComChilkatSocket)) To hoConnection
    If (Not(IsComObjectCreated(hoConnection))) Begin
        Send CreateComObject of hoConnection
    End
    Set ComRequireSslCertVerify Of hoConnection To True
    Set ComMaxReadIdleMs Of hoConnection To 60000
    Set ComMaxSendIdleMs Of hoConnection To 60000
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
    If (iSuccess <> True) Begin
        Showln "TLS connection failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get pvComObject of hoConnection to vConnection
    Get ComUseConnection Of hoRest vConnection True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not attach the TLS connection."
        Procedure_Return
    End

    Get ComAddHeader Of hoRest "x-amz-glacier-version" "2012-06-01" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set x-amz-glacier-version."
        Procedure_Return
    End

    //  A hyphen selects the account belonging to the signing credentials.
    //  Use the original, URL-safe vault name and IDs returned by Glacier.
    Get ComAddPathParam Of hoRest "{vault}" "chilkat" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set vault name."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Get Create (RefClass(cComChilkatJsonObject)) To hoError
    If (Not(IsComObjectCreated(hoError))) Begin
        Send CreateComObject of hoError
    End
    Set ComStrict Of hoError To True
    Get Create (RefClass(cComChilkatStringBuilder)) To hoResponseBody
    If (Not(IsComObjectCreated(hoResponseBody))) Begin
        Send CreateComObject of hoResponseBody
    End
    Move "YOUR_JOB_ID" To sJobId
    Get ComAddPathParam Of hoRest "{job}" sJobId To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set job ID."
        Procedure_Return
    End

    Get pvComObject of hoResponseBody to vResponseBody
    Get ComFullRequestNoBodySb Of hoRest "GET" "/-/vaults/{vault}/jobs/{job}" vResponseBody To iSuccess
    If (iSuccess <> True) Begin
        Showln "Request did not complete; inspect diagnostics privately. Check state before retrying a change."
        Procedure_Return
    End

    Get ComResponseStatusCode Of hoRest To iTemp1
    If (iTemp1 <> 200) Begin
        Get ComResponseStatusCode Of hoRest To iTemp1
        Showln "Glacier HTTP status: " iTemp1
        Get pvComObject of hoResponseBody to vResponseBody
        Get ComLoadSb Of hoError vResponseBody To iSuccess
        If (iSuccess = True) Begin
            Get ComJsonTypeOf Of hoError "code" To iTemp1
            If (iTemp1 = 1) Begin
                Get ComStringOf Of hoError "code" To sTemp1
                Showln "AWS error code: " sTemp1
            End

        End

        Get ComResponseHdrByName Of hoRest "x-amzn-RequestId" To sTemp1
        Showln "AWS request ID: " sTemp1
        //  Inspect full errors privately. An HTTP error is not a successful operation.
        Procedure_Return
    End

    Get pvComObject of hoResponseBody to vResponseBody
    Get ComLoadSb Of hoResult vResponseBody To iSuccess
    If (iSuccess <> True) Begin
        Showln "Expected valid JSON response."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "Completed" To iTemp1
    If (iTemp1 <> 5) Begin
        Showln "Missing or invalid Completed."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "StatusCode" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Missing or invalid StatusCode."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "StatusCode" To sTemp1
    If (sTemp1 = "") Begin
        Showln "Empty StatusCode."
        Procedure_Return
    End

    Get ComBoolOf Of hoResult "Completed" To bTemp1
    Get ComStringOf Of hoResult "StatusCode" To sTemp1
    If ((bTemp1 <> True) Or (sTemp1 <> "Succeeded")) Begin
        Showln "Job is not successfully complete. Resume later only if InProgress."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "Action" To sTemp1
    If (sTemp1 <> "ArchiveRetrieval") Begin
        Showln "Wrong job type."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "SHA256TreeHash" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Missing or invalid SHA256TreeHash."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "SHA256TreeHash" To sTemp1
    If (sTemp1 = "") Begin
        Showln "Empty SHA256TreeHash."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "RetrievalByteRange" To sTemp1
    If (sTemp1 <> "8388608-16777215") Begin
        Showln "Use the 8 MiB range job created by the companion example."
        Procedure_Return
    End

    //  These offsets are relative to the JOB OUTPUT, not the original archive.
    //  Output bytes 0..8388607 correspond to archive bytes 8388608..16777215.
    Get ComStringOf Of hoResult "SHA256TreeHash" To sExpectedHash
    Get Create (RefClass(cComChilkatStringBuilder)) To hoRangeHeader
    If (Not(IsComObjectCreated(hoRangeHeader))) Begin
        Send CreateComObject of hoRangeHeader
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoContentRange
    If (Not(IsComObjectCreated(hoContentRange))) Begin
        Send CreateComObject of hoContentRange
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoByteCount
    If (Not(IsComObjectCreated(hoByteCount))) Begin
        Send CreateComObject of hoByteCount
    End
    Get ComAppend Of hoRangeHeader "bytes=0-8388607" To iSuccess
    Get ComAppend Of hoContentRange "bytes 0-8388607/8388608" To iSuccess
    Get ComAppend Of hoByteCount "8388608" To iSuccess
    Get Create (RefClass(cComCkFileAccess)) To hoFiles
    If (Not(IsComObjectCreated(hoFiles))) Begin
        Send CreateComObject of hoFiles
    End
    Get Create (RefClass(cComChilkatCrypt2)) To hoCrypt
    If (Not(IsComObjectCreated(hoCrypt))) Begin
        Send CreateComObject of hoCrypt
    End
    Set ComHashAlgorithm Of hoCrypt To "sha256-tree-hash"
    Set ComEncodingMode Of hoCrypt To "hexlower"
    Move "qa_output/archive-range.dat.part" To sTemporaryPath
    Move "qa_output/archive-range.dat" To sFinalPath
    Get ComFileExists Of hoFiles sTemporaryPath To bTemp1
    Get ComFileExists Of hoFiles sFinalPath To bTemp2
    If ((bTemp1 = True) Or (bTemp2 = True)) Begin
        Showln "Choose unused output paths."
        Procedure_Return
    End

    Get ComGetAsString Of hoRangeHeader To sTemp1
    Get ComAddHeader Of hoRest "Range" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Range."
        Procedure_Return
    End

    Get ComSendReqNoBody Of hoRest "GET" "/-/vaults/{vault}/jobs/{job}/output" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not send range request. Rerun to resume."
        Procedure_Return
    End

    Get ComReadResponseHeader Of hoRest To iHttpStatus
    If (iHttpStatus <> 206) Begin
        Showln "Expected HTTP 206 for range download. Job may have expired; no new retrieval was started."
        Procedure_Return
    End

    Get ComResponseHdrByName Of hoRest "Content-Range" To sResponseRange
    Get ComLastMethodSuccess Of hoRest To bTemp1
    Get ComGetAsString Of hoContentRange To sTemp1
    If ((bTemp1 <> True) Or (sResponseRange <> sTemp1)) Begin
        Showln "Unexpected Content-Range; refusing download."
        Procedure_Return
    End

    Get ComResponseHdrByName Of hoRest "Content-Length" To sResponseLength
    Get ComLastMethodSuccess Of hoRest To bTemp1
    Get ComGetAsString Of hoByteCount To sTemp1
    If ((bTemp1 <> True) Or (sResponseLength <> sTemp1)) Begin
        Showln "Unexpected Content-Length; refusing download."
        Procedure_Return
    End

    Get ComResponseHdrByName Of hoRest "x-amz-sha256-tree-hash" To sResponseHash
    Get ComLastMethodSuccess Of hoRest To bTemp1
    If ((bTemp1 <> True) Or (sResponseHash = "")) Begin
        Showln "Missing range tree hash. Require a tree-hash-aligned retrieval and download range."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStream)) To hoOutput
    If (Not(IsComObjectCreated(hoOutput))) Begin
        Send CreateComObject of hoOutput
    End
    Set ComSinkFile Of hoOutput To sTemporaryPath
    Get pvComObject of hoOutput to vOutput
    Get ComReadRespBodyStream Of hoRest vOutput True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Download interrupted; rerun to resume. Temporary bytes are not trusted."
        Procedure_Return
    End

    Get ComFileSizeStr Of hoFiles sTemporaryPath To sActualSize
    Get ComLastMethodSuccess Of hoFiles To bTemp1
    Get ComGetAsString Of hoByteCount To sTemp1
    If ((bTemp1 <> True) Or (sActualSize <> sTemp1)) Begin
        Showln "Downloaded size mismatch."
        Procedure_Return
    End

    Get ComHashFileENC Of hoCrypt sTemporaryPath To sActualHash
    Get ComLastMethodSuccess Of hoCrypt To bTemp1
    If ((bTemp1 <> True) Or (sActualHash <> sResponseHash)) Begin
        Showln "Downloaded tree hash mismatch."
        Procedure_Return
    End

    If (sActualHash <> sExpectedHash) Begin
        Showln "Range output does not match the retrieval job tree hash."
        Procedure_Return
    End

    Get ComFileRename Of hoFiles sTemporaryPath sFinalPath To iSuccess
    If (iSuccess <> True) Begin
        Showln "Verified range remains at the temporary path; rename failed."
        Procedure_Return
    End

    Showln "Archive range downloaded and verified."


End_Procedure