ossutil

repository·master·Indexed 19 days ago

https://github.com/aliyun/ossutil

A command-line tool developed in Go for managing data in Alibaba Cloud Object Storage Service (OSS). It enables users to list buckets and objects, upload files, manage multipart upload tasks, and assume RAM roles via the STS Client. The tool distinguishes between Cloud URLs (oss://) and local File URLs and provides a comprehensive CLI for OSS resource management.

Tokens
2.8K
Snippets
10
Records
13
Agent score
68%

What's inside ossutil

  1. Run tests for ossutil

    master

    To run the project's tests, you must first update the test configuration with your own credentials.

    1. Open github.com/aliyun/ossutil/lib/command_test.go.
    2. Update the following configuration values:
      • endpoint
      • AccessKeyId
      • AccessKeySecret
      • STSToken (if applicable)
    3. Navigate to the lib directory and execute go test.
    # Navigate to lib and run tests
    cd lib
    go test
  2. Quick start with ossutil

    master

    ossutil is a command-line tool for managing Alibaba Cloud Object Storage Service (OSS) data. It is built on the official Alibaba Cloud OSS Go SDK.

    Common tasks include:

    • Listing commands: View all available commands.
    • Getting help: View documentation for a specific command.
    • Configuration: Set up your OSS credentials.
    • Listing resources: List buckets, objects, and multipart uploads.
    • File operations: Upload files to a bucket.
    # Get command list
    ./ossutil
    # or
    ./ossutil help
    
    # View help for a specific command
    ./ossutil help cmd
    
    # Configure ossutil
    ./ossutil config
    
    # List buckets
    ./ossutil ls
    # or
    ./ossutil ls oss://
    
    # List objects and Multipart Uploads
    ./ossutil ls -a
    # or
    ./ossutil ls oss:// -a
    
    # Upload a file
    ./ossutil cp localfile oss://bucket
  3. Quick start with OSSUTIL commands

    master

    OSSUTIL provides a command-line interface for managing data in Alibaba Cloud Object Storage Service (OSS). Common tasks include configuring the tool, listing resources, and uploading files.

    # Get the command list
    ./ossutil
    # or
    ./ossutil help
    
    # Configure OSSUTIL
    ./ossutil config
    
    # List buckets
    ./ossutil ls
    # or
    ./ossutil ls oss://
    
    # List objects and multipart upload tasks
    ./ossutil ls -a
    # or
    ./ossutil ls oss:// -a
    
    # Upload a file
    ./ossutil cp localfile oss://bucket
  4. Build ossutil from source

    master

    To build the ossutil tool from the Go source code, follow these steps:

    1. Configure your Go workspace directory.
    2. Fetch the required dependencies using go get.
    3. Navigate to the src directory within the project.
    4. Run go build on the main entry point.

    Example for Linux:

    go build github.com/aliyun/ossutil/ossutil.go
    # Example build command for Linux
    go build github.com/aliyun/ossutil/ossutil.go
  5. Understand OSS and File URL formats in ossutil

    master

    ossutil distinguishes between Cloud URLs (OSS resources) and File URLs (local filesystem paths).

    Cloud URLs

    Cloud URLs represent resources on Alibaba Cloud OSS. They must use the oss:// scheme prefix.

    • Format: oss://<bucket>/<object> or /<bucket>/<object>
    • Example: oss://my-bucket/path/to/object.txt or /my-bucket/object.txt
    • Note: Object names cannot begin with / or \.

    File URLs

    File URLs represent local paths on your machine.

    • Format: Standard filesystem paths.
    • Home Directory: You can use the tilde ~ to represent the current user's home directory (e.g., ~/data/file.txt).
    • Encoding: If the --encoding-type option is used in the CLI, file names will be URL-decoded.
  6. Assume a role using the STS Client

    master

    The AssumeRole method allows you to obtain temporary security credentials by assuming an Alibaba Cloud RAM role. This is useful for implementing the principle of least privilege by using short-lived credentials instead of long-term AccessKey/SecretKey pairs.

    To use this, you must initialize a Client with your permanent credentials and the target RoleArn. The AssumeRole method then returns a Response containing Credentials (including an AccessKeyId, AccessKeySecret, and a SecurityToken) and an AssumedRoleUser object.

    // Initialize the STS client
    stsClient := lib.NewClient("YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET", "arn:aliyun:ram::1234567890:role/YourRoleName", "session-name")
    
    // Assume the role
    // tokenTimeout: duration in seconds for the temporary credentials
    // stsEndPoint: optional custom STS endpoint (e.g., for regional endpoints)
    response, err := stsClient.AssumeRole(3600, "")
    if err != nil {
        log.Fatalf("Failed to assume role: %v", err)
    }
    
    // Use the returned credentials
    fmt.Printf("Temporary AccessKeyId: %s\n", response.Credentials.AccessKeyId)
    fmt.Printf("Security Token: %s\n", response.Credentials.SecurityToken)
    fmt.Printf("Expiration: %v\n", response.Credentials.Expiration)
  7. STS Client configuration and response structures

    master

    The STS client logic relies on several key data structures for configuration and handling responses:

    Client Configuration

    NewClient(accessKeyId, accessKeySecret, roleArn, sessionName string) initializes a client with:

    • AccessKeyId: Your permanent Alibaba Cloud AccessKey ID.
    • AccessKeySecret: Your permanent Alibaba Cloud AccessKey Secret.
    • RoleArn: The ARN of the role you wish to assume.
    • SessionName: An identifier for the assumed role session.

    Response Data

    Successful calls to AssumeRole return a Response containing:

    • Credentials: An object with AccessKeyId, AccessKeySecret, SecurityToken, and Expiration (time.Time).
    • AssumedRoleUser: An object with Arn and AssumedRoleId.
    • RequestId: The unique request ID from the service.
  8. Parse specific OSS Object URLs

    master

    If you need to ensure a URL is specifically an OSS object (containing both a bucket and an object path) rather than just a bucket reference, use ObjectURLFromString. This will return an error if the bucket or object is missing.

    // This will succeed for an object
    cloudURL, err := lib.ObjectURLFromString("oss://my-bucket/my-object", "")
    
    // This will fail if the object part is missing
    cloudURL, err := lib.ObjectURLFromString("oss://my-bucket", "")
    // err: invalid cloud url: oss://my-bucket, miss object
  9. Parse URLs using StorageURLFromString

    master

    The StorageURLFromString function is the primary way to identify whether a provided string is a Cloud URL or a local File URL. It returns a StorageURLer interface which can then be used to check the type or retrieve the string representation.

    If the input starts with oss:// (case-insensitive), it is treated as a CloudURL. Otherwise, it is treated as a FileURL.

    // Example of parsing a URL
    urlStr := "oss://my-bucket/my-object"
    encodingType := "" // or URLEncodingType
    
    storageURL, err := lib.StorageURLFromString(urlStr, encodingType)
    if err != nil {
        // handle error
    }
    
    if storageURL.IsCloudURL() {
        fmt.Println("This is an OSS resource")
    } else if storageURL.IsFileURL() {
        fmt.Println("This is a local file")
    }
  10. Run ossutil commands via the main entrypoint

    master

    The ossutil CLI is executed by calling lib.ParseAndRunCommand(). This function handles command-line argument parsing and dispatches the appropriate command execution.

    If the execution fails, the entrypoint provides specific handling for common error scenarios:

    1. NoSuchUpload Error: If the error contains ErrorCode=NoSuchUpload, the tool automatically removes the directory specified by lib.CheckpointDir to clear corrupted state before exiting.
    2. EOF/Connection Errors: If the error contains : EOF,, it indicates the connection was closed by the remote peer. The tool suggests:
      • Reducing concurrency using the --parallel option.
      • Reducing part size using the --part-size option (must be greater than file_size / 10000).
      • Increasing retry attempts using the --retry-times option.
    package main
    
    import (
    	"fmt"
    	"os"
    	"strings"
    	"github.com/aliyun/ossutil/lib"
    )
    
    func main() {
    	if err := lib.ParseAndRunCommand(); err != nil {
    		fmt.Printf("Error: %s\n", err)
    		// ... error handling logic ...
    		os.Exit(1)
    	}
    	os.Exit(0)
    }
  11. Handle STS service errors

    master

    When an STS request fails, the client returns a ServiceError. This error type provides structured information about why the request was rejected by the Alibaba Cloud STS service. You can inspect the following fields to debug issues:

    • Code: The error code (e.g., InvalidAccessKeyId or AccessDenied).
    • Message: A human-readable description of the error.
    • RequestId: The unique ID for the request, which can be used for support inquiries.
    • StatusCode: The HTTP status code returned by the server.
    type ServiceError struct {
    	Code       string
    	Message    string
    	RequestId  string
    	HostId     string
    	RawMessage string
    	StatusCode int
    }