Listar snapshots

Demonstra como listar snapshots.

Exemplo de código

C#

Para autenticar no Dataflow, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

using Google.Cloud.Dataflow.V1Beta3;

public sealed partial class GeneratedSnapshotsV1Beta3ClientSnippets
{
    /// <summary>Snippet for ListSnapshots</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void ListSnapshotsRequestObject()
    {
        // Create client
        SnapshotsV1Beta3Client snapshotsV1Beta3Client = SnapshotsV1Beta3Client.Create();
        // Initialize request argument(s)
        ListSnapshotsRequest request = new ListSnapshotsRequest
        {
            ProjectId = "",
            Location = "",
            JobId = "",
        };
        // Make the request
        ListSnapshotsResponse response = snapshotsV1Beta3Client.ListSnapshots(request);
    }
}

Go

Para autenticar no Dataflow, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import (
	"context"
	"fmt"
	"io"
	"os"

	dataflow "cloud.google.com/go/dataflow/apiv1beta3"
	"cloud.google.com/go/dataflow/apiv1beta3/dataflowpb"
)

// listSnapshots lists Dataflow snapshots in a project and location.
func listSnapshots(ctx context.Context, w io.Writer) error {
	client, err := dataflow.NewSnapshotsV1Beta3Client(ctx)
	if err != nil {
		return fmt.Errorf("NewSnapshotsV1Beta3Client: %w", err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	if projectID == "" {
		projectID = os.Getenv("GCP_PROJECT")
	}
	jobID := os.Getenv("DATAFLOW_JOB_ID")

	req := &dataflowpb.ListSnapshotsRequest{
		ProjectId: projectID,
		Location:  "us-central1",
		JobId:     jobID,
	}

	resp, err := client.ListSnapshots(ctx, req)
	if err != nil {
		return fmt.Errorf("ListSnapshots: %w", err)
	}

	snapshots := resp.GetSnapshots()
	if len(snapshots) == 0 {
		fmt.Fprintln(w, "No snapshots found.")
		return nil
	}

	for _, snapshot := range snapshots {
		fmt.Fprintf(w, "Snapshot ID: %s, State: %s\n", snapshot.GetId(), snapshot.GetState())
	}

	return nil
}

Java

Para autenticar no Dataflow, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.dataflow.v1beta3.ListSnapshotsRequest;
import com.google.dataflow.v1beta3.ListSnapshotsResponse;
import com.google.dataflow.v1beta3.SnapshotsV1Beta3Client;

public class SyncListSnapshots {

  public static void main(String[] args) throws Exception {
    syncListSnapshots();
  }

  public static void syncListSnapshots() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (SnapshotsV1Beta3Client snapshotsV1Beta3Client = SnapshotsV1Beta3Client.create()) {
      ListSnapshotsRequest request =
          ListSnapshotsRequest.newBuilder()
              .setProjectId("projectId-894832108")
              .setJobId("jobId101296568")
              .setLocation("location1901043637")
              .build();
      ListSnapshotsResponse response = snapshotsV1Beta3Client.listSnapshots(request);
    }
  }
}

Node.js

Para autenticar no Dataflow, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

'use strict';

const {SnapshotsV1Beta3Client} = require('@google-cloud/dataflow');
const {status} = require('@grpc/grpc-js');

const client = new SnapshotsV1Beta3Client();

/**
 * Use the listSnapshots method
 *
 * @param {string} projectId - The Google Cloud project ID to list snapshots for.
 * @param {string} locationId - The Google Cloud region to list snapshots in (e.g., 'us-central1').
 * @param {string} jobId - The server-generated ID of the Dataflow job to list snapshots for.
 */
async function listSnapshots(projectId, locationId, jobId) {
  try {
    const request = {
      projectId,
      location: locationId,
      jobId,
    };

    const [response] = await client.listSnapshots(request);

    if (response.snapshots && response.snapshots.length > 0) {
      for (const snapshot of response.snapshots) {
        console.log(`Snapshot ID: ${snapshot.id}`);
        console.log(`State: ${snapshot.state}`);
        console.log(`Source Job ID: ${snapshot.sourceJobId}`);
      }
    } else {
      console.log('No snapshots found for the specified Dataflow job.');
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Job or snapshot resource not found: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      console.error(`API request failed: ${err.message}`);
    }
  }
}

module.exports = { listSnapshots };

Python

Para autenticar no Dataflow, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import google.api_core.exceptions
from google.cloud import dataflow_v1beta3


def list_snapshots(project_id: str, location_id: str, job_id: str) -> None:
    """Lists snapshots for a Cloud Dataflow job in a Google Cloud project.

    Args:
        project_id: The ID of the Google Cloud project that contains the job.
        location_id: The Google Cloud region where the Dataflow job executed.
        job_id: The server-generated ID of the Dataflow job.
    """
    client = dataflow_v1beta3.SnapshotsV1Beta3Client()

    request = dataflow_v1beta3.ListSnapshotsRequest(
        project_id=project_id,
        location=location_id,
        job_id=job_id,
    )

    try:
        response = client.list_snapshots(request=request)
        print(f"Found {len(response.snapshots)} snapshots for job {job_id}.")
        for snapshot in response.snapshots:
            print(f"Snapshot ID: {snapshot.id}")
            print(f"State: {snapshot.state}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"API call failed: {error}")

A seguir

Para pesquisar e filtrar exemplos de código de outros Google Cloud produtos, consulte a Google Cloud pesquisa de exemplos de código.