Working with long-running operations

Várias operações solicitadas são de longa execução, como treinamento de modelo, importação de arquivo em um conjunto de dados e exclusão de modelo. Esses tipos de pedidos retornarão um JSON com um ID de operação que pode ser usado para ver o status da operação.

Por exemplo, uma solicitação de treinamento de modelo retorna o seguinte JSON:

        {
          "name": "projects/project-id/locations/us-central1/operations/ICN3074819451447672458",
          "metadata": {
            "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
            "createTime": "2019-07-26T21:10:18.338846Z",
            "updateTime": "2019-07-26T21:10:18.338846Z",
            "createModelDetails": {}
          }
        }
        

Nesse caso, o ID da operação é ICN3074819451447672458. Os exemplos a seguir mostram como ver o status desta operação com esse ID.

Ver exemplos de código de operação

REST e LINHA DE COMANDO

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • project-id: o ID do projeto do GCP
  • operation-id: o ID da sua operação. O ID é o último elemento do nome da sua operação. Por exemplo:
    • nome da operação: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • ID de operação:: IOD5281059901324392598

Método HTTP e URL:

GET https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/operations/operation-id

Para enviar a solicitação, escolha uma destas opções:

curl

Execute o comando a seguir:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/operations/operation-id

PowerShell

Execute o comando a seguir:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/operations/operation-id" | Select-Object -Expand Content
Você verá uma saída semelhante à seguinte para uma operação de importação concluída:
{
      "name": "projects/project-id/locations/us-central1/operations/operation-id",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
        "createTime": "2018-10-29T15:56:29.176485Z",
        "updateTime": "2018-10-29T16:10:41.326614Z",
        "importDataDetails": {}
      },
      "done": true,
      "response": {
        "@type": "type.googleapis.com/google.protobuf.Empty"
      }
    }

Você verá uma saída semelhante à seguinte para uma operação de modelo de criação concluída:

    {
      "name": "projects/project-id/locations/us-central1/operations/operation-id",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
        "createTime": "2019-07-22T18:35:06.881193Z",
        "updateTime": "2019-07-22T19:58:44.972235Z",
        "createModelDetails": {}
      },
      "done": true,
      "response": {
        "@type": "type.googleapis.com/google.cloud.automl.v1.Model",
        "name": "projects/project-id/locations/us-central1/models/model-id"
      }
    }
    

C#

Ver no GitHub (em inglês) Feedback
/// <summary>
    /// Demonstrates using the AutoML client to get operation status.
    /// </summary>
    /// <param name="operationFullId">the complete name of a operation. For example, the name of your
    /// operation is projects/[projectId]/locations/us-central1/operations/[operationId].</param>
    public static object GetOperationStatus(string operationFullId
        = "projects/[projectId]/locations/us-central1/operations/[operationId]")
    {
        // Initialize the client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        AutoMlClient client = AutoMlClient.Create();

        // Get the latest state of a long-running operation.
        //TODO: I dont know why there is no 'GetOperationsClient'
        Operation operation = client.CreateModelOperationsClient.GetOperation(operationFullId);

        // Display operation details.
        Console.WriteLine("Operation details:");
        Console.WriteLine($"\tName: {operation.Name}");
        Console.WriteLine($"\tMetadata Type Url: {operation.Metadata.TypeUrl}");
        Console.WriteLine($"\tDone: {operation.Done}");
        if (operation.Response != null)
        {
            Console.WriteLine($"\tResponse Type Url: {operation.Response.TypeUrl}");
        }
        if (operation.Error != null)
        {
            Console.WriteLine("\tResponse:");
            Console.WriteLine($"\t\tError code: {operation.Error.Code}");
            Console.WriteLine($"\t\tError message: {operation.Error.Message}");
        }

        return 0;
    }
    

Go

Ver no GitHub (em inglês) Feedback
import (
    	"context"
    	"fmt"
    	"io"

    	automl "cloud.google.com/go/automl/apiv1"
    	"google.golang.org/genproto/googleapis/longrunning"
    )

    // getOperationStatus gets an operation's status.
    func getOperationStatus(w io.Writer, projectID string, location string, operationID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// operationID := "TRL123456789..."

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

    	req := &longrunning.GetOperationRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/operations/%s", projectID, location, operationID),
    	}

    	op, err := client.LROClient.GetOperation(ctx, req)
    	if err != nil {
    		return fmt.Errorf("GetOperation: %v", err)
    	}

    	fmt.Fprintf(w, "Name: %v\n", op.GetName())
    	fmt.Fprintf(w, "Operation details:\n")
    	fmt.Fprintf(w, "%v", op)

    	return nil
    }
    

Java

Ver no GitHub (em inglês) Feedback
import com.google.cloud.automl.v1.AutoMlClient;
    import com.google.longrunning.Operation;

    import java.io.IOException;

    class GetOperationStatus {

      static void getOperationStatus() throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String operationFullId = "projects/[projectId]/locations/us-central1/operations/[operationId]";
        getOperationStatus(operationFullId);
      }

      // Get the status of an operation
      static void getOperationStatus(String operationFullId) throws IOException {
        // 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.
        try (AutoMlClient client = AutoMlClient.create()) {
          // Get the latest state of a long-running operation.
          Operation operation = client.getOperationsClient().getOperation(operationFullId);

          // Display operation details.
          System.out.println("Operation details:");
          System.out.format("\tName: %s\n", operation.getName());
          System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
          System.out.format("\tDone: %s\n", operation.getDone());
          if (operation.hasResponse()) {
            System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
          }
          if (operation.hasError()) {
            System.out.println("\tResponse:");
            System.out.format("\t\tError code: %s\n", operation.getError().getCode());
            System.out.format("\t\tError message: %s\n", operation.getError().getMessage());
          }
        }
      }
    }

Node.js

Ver no GitHub (em inglês) Feedback
/**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'YOUR_PROJECT_ID';
    // const location = 'us-central1';
    // const operationId = 'YOUR_OPERATION_ID';

    // Imports the Google Cloud AutoML library
    const {AutoMlClient} = require(`@google-cloud/automl`).v1;

    // Instantiates a client
    const client = new AutoMlClient();

    async function getOperationStatus() {
      // Construct request
      const request = {
        name: `projects/${projectId}/locations/${location}/operations/${operationId}`,
      };

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

      console.log(`Name: ${response.name}`);
      console.log(`Operation details:`);
      console.log(`${response}`);
    }

    getOperationStatus();

PHP

Ver no GitHub (em inglês) Feedback
use Google\ApiCore\LongRunning\OperationsClient;

    /** Uncomment and populate these variables in your code */
    // $projectId = '[Google Cloud Project ID]';
    // $location = 'us-central1';
    // $operationId = 'my_operation_id_123';

    $client = new OperationsClient();

    try {
        // full name of operation
        $formattedName = 'projects/' . $projectId . '/locations/us-central1/operations/' . $operationId;

        // get latest state of long running operation
        $operation = $client->getOperation($name);
        printf('Operation name: %s' . PHP_EOL, $operation->getName());
        print('Operation details: ');
        print($operation);
    } finally {
        if (isset($client)) {
            $client->close();
        }
    }

Python

Ver no GitHub (em inglês) Feedback
from google.cloud import automl

    # TODO(developer): Uncomment and set the following variables
    # operation_full_id = \
    #     "projects/[projectId]/locations/us-central1/operations/[operationId]"

    client = automl.AutoMlClient()
    # Get the latest state of a long-running operation.
    response = client.transport._operations_client.get_operation(
        operation_full_id
    )

    print("Name: {}".format(response.name))
    print("Operation details:")
    print(response)