Trasferire file o oggetti specifici utilizzando un manifest

Storage Transfer Service supporta il trasferimento di file o oggetti specifici, specificati utilizzando un manifest. Un manifest è un file CSV, caricato su Cloud Storage, che contiene un elenco di file o oggetti su cui Storage Transfer Service deve agire.

Un manifest può essere utilizzato per i seguenti trasferimenti:

  • Da AWS S3, spazio di archiviazione compatibile con S3, Azure Blobstore o Cloud Storage a un bucket Cloud Storage.

  • Da un file system a un bucket Cloud Storage.

  • Da un bucket Cloud Storage a un file system.

  • Tra due file system.

  • Da un'origine HTTP/HTTPS accessibile pubblicamente a un bucket Cloud Storage. Segui le istruzioni riportate in Creare un elenco di URL, poiché il formato del manifest è univoco per gli elenchi di URL.

Creare un manifest

I file manifest hanno i seguenti requisiti:

  • I manifest devono essere formattati come CSV.
  • Possono contenere qualsiasi carattere UTF-8.
  • La prima colonna deve essere un nome file o un nome oggetto. Il nome è relativo a percorso root o al bucket e alla cartella specificati nel job di trasferimento. Per i dettagli, consulta Trasferimenti di file system e Trasferimenti di archiviazione di oggetti.
  • I file manifest non supportano i caratteri jolly. I nomi delle cartelle senza un nome file o oggetto non sono supportati.
  • Se un nome file o oggetto contiene una virgola, il nome deve essere racchiuso tra virgolette doppie. Ad esempio, "doe,john.txt".
  • Non esiste un limite alla dimensione del file manifest.

Ti consigliamo di testare il trasferimento con un piccolo sottoinsieme di file o oggetti per evitare chiamate API non necessarie a causa di errori di configurazione.

Puoi monitorare lo stato dei trasferimenti di file dalla pagina Job di trasferimento. I file o gli oggetti di cui non è stato eseguito il trasferimento sono elencati nei log di trasferimento.

Trasferimenti di file system

Per creare un manifest dei file in un file system, crea un file CSV con una singola colonna contenente i percorsi dei file relativi alla directory root specificata nella creazione del job di trasferimento.

Ad esempio, per trasferire i seguenti file del file system:

Percorso file
rootdir/dir1/subdir1/file1.txt
rootdir/file2.txt
rootdir/dir2/subdir1/file3.txt

Il manifest dovrebbe essere simile all'esempio seguente:

dir1/subdir1/file1.txt
file2.txt
dir2/subdir1/file3.txt

Salva il file manifest con qualsiasi nome file e un'estensione .csv.

Trasferimenti di archiviazione di oggetti

Per creare un manifest di oggetti, crea un file CSV la cui prima colonna contiene i nomi degli oggetti relativi al nome e al percorso del bucket specificati nella creazione del job di trasferimento. Tutti gli oggetti devono trovarsi nello stesso bucket.

Puoi anche specificare una seconda colonna facoltativa con il numero di generazione di Cloud Storage della versione specifica da trasferire.

Ad esempio, potresti voler trasferire i seguenti oggetti:

Percorso oggetto Numero di generazione di Cloud Storage
SOURCE_PATH/object1.pdf 1664826685911832
SOURCE_PATH/object2.pdf
SOURCE_PATH/object3.pdf 1664826610699837

Il manifest dovrebbe essere simile all'esempio seguente:

object1.pdf,1664826685911832
object2.pdf
object3.pdf,1664826610699837

Salva il file manifest con qualsiasi nome file e un'estensione .csv.

Trasferimenti HTTP/HTTPS

Per trasferire file specifici da un'origine HTTP o HTTPS, consulta le istruzioni riportate in Creare un elenco di URL.

Pubblicare il manifest

Una volta creato il manifest, devi renderlo disponibile per Storage Transfer Service. Storage Transfer Service può accedere al file in un bucket Cloud Storage o nel file system.

Caricare il manifest su Cloud Storage

Puoi archiviare il file manifest in qualsiasi bucket Cloud Storage.

Il service agent che esegue il trasferimento deve disporre dell'autorizzazione storage.objects.get per il bucket contenente il manifest. Per istruzioni su come trovare l'ID del service agent e concedere le autorizzazioni a questo service agent su un bucket, consulta Concedere le autorizzazioni richieste.

Per istruzioni su come caricare il manifest in un bucket, consulta Caricare oggetti nella documentazione di Cloud Storage.

Ad esempio, per utilizzare la gcloud CLI per caricare un file su Cloud Storage, utilizza il comando gcloud storage cp:

gcloud storage cp MANIFEST.CSV gs://DESTINATION_BUCKET_NAME/

Sostituisci quanto segue:

  • MANIFEST.CSV è il percorso locale del file manifest. Ad esempio, Desktop/manifest01.csv.

  • DESTINATION_BUCKET_NAME è il nome del bucket in cui stai caricando l'oggetto. Ad esempio, my-bucket.

In caso di esito positivo, la risposta sarà simile all'esempio seguente:

Completed files 1/1 | 164.3kiB/164.3kiB

Puoi criptare un manifest utilizzando le chiavi di crittografia Cloud KMS gestite dal cliente. In questo caso, assicurati che a tutti i service account che accedono al manifest siano assegnate le chiavi di crittografia applicabili. Le chiavi fornite dal cliente non sono supportate.

Archiviare il manifest in un file system

Puoi archiviare il file manifest nel file system di origine o di destinazione.

La posizione del file deve essere accessibile agli agenti di trasferimento. Se limiti l'accesso alle directory per gli agenti, assicurati che il file manifest si trovi all'interno di una directory montata.

Avviare un trasferimento

Non modificare il file manifest finché non viene completata un'operazione di trasferimento. Ti consigliamo di bloccare il file manifest durante un trasferimento.

console Cloud

Per avviare un trasferimento con un manifest dalla console Cloud:

  1. Segui le istruzioni riportate in Creare trasferimenti per selezionare l' origine, la destinazione e le opzioni.

  2. Nell'ultimo passaggio, Scegli impostazioni, seleziona la casella di controllo Fornisci l'elenco dei file da trasferire tramite il file manifest.

  3. Inserisci la posizione del file manifest.

gcloud

Per trasferire i file o gli oggetti elencati nel manifest, includi il --manifest-file=MANIFEST_FILE flag con il tuo gcloud transfer jobs create comando.

gcloud transfer jobs create SOURCE DESTINATION \
  --manifest-file=MANIFEST_FILE

MANIFEST_FILE può essere uno dei seguenti valori:

  • Il percorso del file CSV in un bucket Cloud Storage:

    --manifest-file=gs://my_bucket/sample_manifest.csv
    

    Per i dettagli sulle autorizzazioni richieste, se il bucket o il file non è pubblico, consulta Caricare il manifest su Cloud Storage.

  • Il percorso relativo dall'origine del file system SOURCE, incluso qualsiasi percorso specificato:

    --manifest-file=source://relative_path/sample_manifest.csv
    
  • Il percorso relativo dal file system DESTINATION, incluso qualsiasi percorso specificato:

    --manifest-file=destination://relative_path/sample_manifest.csv
    

REST + Librerie client

REST

Per trasferire i file o gli oggetti elencati nel manifest, effettua una chiamata API createTransferJob che specifica un transferSpec con il campo transferManifest aggiunto. Ad esempio:

POST https://storagetransfer.googleapis.com/v1/transferJobs

...
  "transferSpec": {
      "posixDataSource": {
          "rootDirectory": "/home/",
      },
      "gcsDataSink": {
          "bucketName": "GCS_NEARLINE_SINK_NAME",
          "path": "GCS_SINK_PATH",
      },
      "transferManifest": {
          "location": "gs://my_bucket/sample_manifest.csv"
      }
  }

Il file manifest può essere archiviato in un bucket Cloud Storage o nel file system di origine o di destinazione. I bucket Cloud Storage devono utilizzare il prefisso gs:// e includere il percorso completo, incluso il nome del bucket. Le posizioni del file system devono utilizzare un prefisso source:// o destination:// e sono relative all'origine o alla destinazione del file system e alla directory root facoltativa.

Vai


import (
	"context"
	"fmt"
	"io"

	storagetransfer "cloud.google.com/go/storagetransfer/apiv1"
	"cloud.google.com/go/storagetransfer/apiv1/storagetransferpb"
)

func transferUsingManifest(w io.Writer, projectID string, sourceAgentPoolName string, rootDirectory string, gcsSinkBucket string, manifestBucket string, manifestObjectName string) (*storagetransferpb.TransferJob, error) {
	// Your project id
	// projectId := "myproject-id"

	// The agent pool associated with the POSIX data source. If not provided, defaults to the default agent
	// sourceAgentPoolName := "projects/my-project/agentPools/transfer_service_default"

	// The root directory path on the source filesystem
	// rootDirectory := "/directory/to/transfer/source"

	// The ID of the GCS bucket to transfer data to
	// gcsSinkBucket := "my-sink-bucket"

	// The ID of the GCS bucket that contains the manifest file
	// manifestBucket := "my-manifest-bucket"

	// The name of the manifest file in manifestBucket that specifies which objects to transfer
	// manifestObjectName := "path/to/manifest.csv"

	ctx := context.Background()
	client, err := storagetransfer.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storagetransfer.NewClient: %w", err)
	}
	defer client.Close()

	manifestLocation := "gs://" + manifestBucket + "/" + manifestObjectName
	req := &storagetransferpb.CreateTransferJobRequest{
		TransferJob: &storagetransferpb.TransferJob{
			ProjectId: projectID,
			TransferSpec: &storagetransferpb.TransferSpec{
				SourceAgentPoolName: sourceAgentPoolName,
				DataSource: &storagetransferpb.TransferSpec_PosixDataSource{
					PosixDataSource: &storagetransferpb.PosixFilesystem{RootDirectory: rootDirectory},
				},
				DataSink: &storagetransferpb.TransferSpec_GcsDataSink{
					GcsDataSink: &storagetransferpb.GcsData{BucketName: gcsSinkBucket},
				},
				TransferManifest: &storagetransferpb.TransferManifest{Location: manifestLocation},
			},
			Status: storagetransferpb.TransferJob_ENABLED,
		},
	}

	resp, err := client.CreateTransferJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create transfer job: %w", err)
	}
	if _, err = client.RunTransferJob(ctx, &storagetransferpb.RunTransferJobRequest{
		ProjectId: projectID,
		JobName:   resp.Name,
	}); err != nil {
		return nil, fmt.Errorf("failed to run transfer job: %w", err)
	}
	fmt.Fprintf(w, "Created and ran transfer job from %v to %v using manifest file %v with name %v", rootDirectory, gcsSinkBucket, manifestLocation, resp.Name)
	return resp, nil
}

Java


import com.google.storagetransfer.v1.proto.StorageTransferServiceClient;
import com.google.storagetransfer.v1.proto.TransferProto;
import com.google.storagetransfer.v1.proto.TransferTypes.GcsData;
import com.google.storagetransfer.v1.proto.TransferTypes.PosixFilesystem;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferManifest;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferSpec;
import java.io.IOException;

public class TransferUsingManifest {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your project id
    String projectId = "my-project-id";

    // The agent pool associated with the POSIX data source. If not provided, defaults to the
    // default agent
    String sourceAgentPoolName = "projects/my-project-id/agentPools/transfer_service_default";

    // The root directory path on the source filesystem
    String rootDirectory = "/directory/to/transfer/source";

    // The ID of the GCS bucket to transfer data to
    String gcsSinkBucket = "my-sink-bucket";

    // The ID of the GCS bucket which has your manifest file
    String manifestBucket = "my-bucket";

    // The ID of the object in manifestBucket that specifies which files to transfer
    String manifestObjectName = "path/to/manifest.csv";

    transferUsingManifest(
        projectId,
        sourceAgentPoolName,
        rootDirectory,
        gcsSinkBucket,
        manifestBucket,
        manifestObjectName);
  }

  public static void transferUsingManifest(
      String projectId,
      String sourceAgentPoolName,
      String rootDirectory,
      String gcsSinkBucket,
      String manifestBucket,
      String manifestObjectName)
      throws IOException {
    String manifestLocation = "gs://" + manifestBucket + "/" + manifestObjectName;
    TransferJob transferJob =
        TransferJob.newBuilder()
            .setProjectId(projectId)
            .setTransferSpec(
                TransferSpec.newBuilder()
                    .setSourceAgentPoolName(sourceAgentPoolName)
                    .setPosixDataSource(
                        PosixFilesystem.newBuilder().setRootDirectory(rootDirectory).build())
                    .setGcsDataSink((GcsData.newBuilder().setBucketName(gcsSinkBucket)).build())
                    .setTransferManifest(
                        TransferManifest.newBuilder().setLocation(manifestLocation).build()))
            .setStatus(TransferJob.Status.ENABLED)
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources,
    // or use "try-with-close" statement to do this automatically.
    try (StorageTransferServiceClient storageTransfer = StorageTransferServiceClient.create()) {

      // Create the transfer job
      TransferJob response =
          storageTransfer.createTransferJob(
              TransferProto.CreateTransferJobRequest.newBuilder()
                  .setTransferJob(transferJob)
                  .build());

      System.out.println(
          "Created and ran a transfer job from "
              + rootDirectory
              + " to "
              + gcsSinkBucket
              + " using "
              + "manifest file "
              + manifestLocation
              + " with name "
              + response.getName());
    }
  }
}

Node.js


// Imports the Google Cloud client library
const {
  StorageTransferServiceClient,
} = require('@google-cloud/storage-transfer');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// Your project id
// const projectId = 'my-project'

// The agent pool associated with the POSIX data source. Defaults to the default agent
// const sourceAgentPoolName = 'projects/my-project/agentPools/transfer_service_default'

// The root directory path on the source filesystem
// const rootDirectory = '/directory/to/transfer/source'

// The ID of the GCS bucket to transfer data to
// const gcsSinkBucket = 'my-sink-bucket'

// Transfer manifest location. Must be a `gs:` URL
// const manifestLocation = 'gs://my-bucket/sample_manifest.csv'

// Creates a client
const client = new StorageTransferServiceClient();

/**
 * Creates a request to transfer from the local file system to the sink bucket
 */
async function transferViaManifest() {
  const createRequest = {
    transferJob: {
      projectId,
      transferSpec: {
        sourceAgentPoolName,
        posixDataSource: {
          rootDirectory,
        },
        gcsDataSink: {bucketName: gcsSinkBucket},
        transferManifest: {
          location: manifestLocation,
        },
      },
      status: 'ENABLED',
    },
  };

  // Runs the request and creates the job
  const [transferJob] = await client.createTransferJob(createRequest);

  const runRequest = {
    jobName: transferJob.name,
    projectId: projectId,
  };

  await client.runTransferJob(runRequest);

  console.log(
    `Created and ran a transfer job from '${rootDirectory}' to '${gcsSinkBucket}' using manifest \`${manifestLocation}\` with name ${transferJob.name}`
  );
}

transferViaManifest();

Python

from google.cloud import storage_transfer


def create_transfer_with_manifest(
    project_id: str,
    description: str,
    source_agent_pool_name: str,
    root_directory: str,
    sink_bucket: str,
    manifest_location: str,
):
    """Create a transfer from a POSIX file system to a GCS bucket using
    a manifest file."""

    client = storage_transfer.StorageTransferServiceClient()

    # The ID of the Google Cloud Platform Project that owns the job
    # project_id = 'my-project-id'

    # A useful description for your transfer job
    # description = 'My transfer job'

    # The agent pool associated with the POSIX data source.
    # Defaults to 'projects/{project_id}/agentPools/transfer_service_default'
    # source_agent_pool_name = 'projects/my-project/agentPools/my-agent'

    # The root directory path on the source filesystem
    # root_directory = '/directory/to/transfer/source'

    # Google Cloud Storage destination bucket name
    # sink_bucket = 'my-gcs-destination-bucket'

    # Transfer manifest location. Must be a `gs:` URL
    # manifest_location = 'gs://my-bucket/sample_manifest.csv'

    transfer_job_request = storage_transfer.CreateTransferJobRequest(
        {
            "transfer_job": {
                "project_id": project_id,
                "description": description,
                "status": storage_transfer.TransferJob.Status.ENABLED,
                "transfer_spec": {
                    "source_agent_pool_name": source_agent_pool_name,
                    "posix_data_source": {
                        "root_directory": root_directory,
                    },
                    "gcs_data_sink": {
                        "bucket_name": sink_bucket,
                    },
                    "transfer_manifest": {"location": manifest_location},
                },
            }
        }
    )

    result = client.create_transfer_job(transfer_job_request)
    print(f"Created transferJob: {result.name}")

Gli oggetti o i file nel manifest non vengono necessariamente trasferiti nell' ordine in cui sono elencati.

Se il manifest include file già esistenti nella destinazione, questi file vengono ignorati, a meno che non sia specificata l'opzione Sovrascrivi gli oggetti già esistenti nel sink.

Se il manifest include oggetti esistenti in una versione diversa nella destinazione, l'oggetto nella destinazione viene sovrascritto con la versione di origine dell'oggetto. Se la destinazione è un bucket con controllo delle versioni, viene creata una nuova versione dell'oggetto.

Passaggi successivi