Trasferisci file o oggetti specifici utilizzando un manifest

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

Un manifest può essere utilizzato per i seguenti trasferimenti:

  • Da AWS S3, Azure Blobstore o Cloud Storage a un bucket Cloud Storage.

  • Da un file system a un bucket Cloud Storage.

  • Dallo spazio di archiviazione compatibile con S3 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 nella pagina Creare un elenco di URL poiché il formato manifest è univoco per gli elenchi di URL.

Crea un manifest

I manifest devono essere formattati come CSV e possono contenere qualsiasi carattere UTF-8. La prima colonna deve essere un percorso file o un nome oggetto specificato come stringa.

La dimensione massima del file manifest è 1 GiB, il che si traduce in circa 1 milione di righe. Se devi trasferire un file manifest di dimensioni superiori a 1 GiB, puoi dividerlo in più file ed eseguire più job di trasferimento.

Se il nome di un file o di un oggetto contiene virgole, deve essere racchiuso tra virgolette doppie, in base agli standard CSV. Ad esempio, "object1,a.txt".

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 dei job di trasferimento. I file o gli oggetti che non vengono trasferiti sono elencati nei log di trasferimento.

Trasferimenti di file system

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

Ad esempio, potresti voler trasferire i seguenti file system:

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

Il file manifest dovrebbe essere simile all'esempio seguente:

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

Trasferimenti di oggetti archiviati

Per creare un manifest degli 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 file 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.

Pubblica il manifest

Dopo aver creato il manifest, devi renderlo disponibile a Storage Transfer Service. Storage Transfer Service può accedere al file in un bucket Cloud Storage o nel file system.

Carica il manifest su Cloud Storage

Puoi archiviare il file manifest in qualsiasi bucket Cloud Storage.

L'agente di servizio che esegue il trasferimento deve avere l'autorizzazione storage.objects.get per il bucket contenente il manifest. Consulta Concedi le autorizzazioni richieste per istruzioni su come trovare l'ID agente di servizio e sulle autorizzazioni per l'agente di servizio su un bucket.

Per istruzioni sul caricamento del manifest in un bucket, consulta la pagina Caricare gli oggetti nella documentazione di Cloud Storage.

Ad esempio, per utilizzare l'interfaccia a riga di comando gcloud per caricare un file in Cloud Storage, utilizza il comando gcloud storage cp:

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

Dove:

  • MANIFEST.CSV è il percorso locale del tuo 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 avrà il seguente esempio:

Completed files 1/1 | 164.3kiB/164.3kiB

Puoi criptare un manifest con le chiavi di crittografia Cloud KMS gestite dal cliente. In questo caso, assicurati che agli account di servizio che accedono al manifest siano assegnate le chiavi di crittografia applicabili. Le chiavi fornite dal cliente non sono supportate.

Archivia il manifest su un file system

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

La posizione del file deve essere accessibile agli agenti trasferiti. Se limiti l'accesso alla directory per gli agenti, assicurati che il file manifest si trovi in una directory montata.

Avviare un trasferimento

Non modificare il file manifest fino al completamento di un'operazione di trasferimento. Ti consigliamo di bloccare il file manifest quando viene eseguito 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. Nel passaggio finale, Scegli le impostazioni, seleziona la casella di controllo Fornisci l'elenco dei file da trasferire tramite il file manifest.

  3. Inserisci il percorso del file manifest.

gcloud

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

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

MANIFEST_FILE può essere uno qualsiasi dei seguenti valori:

  • Il percorso al 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 sono pubblici, consulta Caricare il manifest in Cloud Storage.

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

    --manifest-file=source://relative_path/sample_manifest.csv
    
  • Il percorso relativo del file system DESTINATION, incluso il 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 oppure 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 località del file system devono utilizzare un prefisso source:// o destination:// e sono relative all'origine o alla destinazione del file system, nonché la directory principale facoltativa.

Go


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 indicato.

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

Se il manifest include oggetti che esistono 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