Visualizza offerte di lavoro e attività

Questo documento spiega come visualizzare le attività e i job batch.

Prima di iniziare

  • Se non hai mai utilizzato Batch, rivedi Inizia a utilizzare Batch e abilita Batch, completando prerequisiti per progetti e utenti.
  • Per ottenere le autorizzazioni necessarie per visualizzare job e attività, chiedi all'amministratore di concederti Visualizzatore job batch (roles/batch.jobsViewer) o editor job batch (roles/batch.jobsEditor) ruolo IAM per il progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso.

    Potresti anche riuscire a ottenere le autorizzazioni richieste tramite la ruoli o altri ruoli predefiniti ruoli.

Visualizza le tue offerte di lavoro

Per visualizzare i job, seleziona uno dei seguenti metodi:

Visualizzare un elenco delle offerte di lavoro

Puoi visualizzare un elenco di job nel progetto corrente utilizzando il console Google Cloud, gcloud CLI, API Batch, Go, Java, Node.js, Python o C++.

Console

  1. Per visualizzare un elenco di job nel progetto corrente utilizzando il comando Nella console Google Cloud, vai alla pagina Elenco job.

    Vai all'elenco dei job

    L'elenco dei job potrebbe essere composto da più pagine. Se devi passare alla pagina successiva, fai clic su Avanti in basso della schermata.

  2. (Facoltativo) Se vuoi filtrare l'elenco dei job, fai clic su Filtro. Poi, o selezionare una proprietà e un valore.

    Ad esempio, per filtrare l'elenco e includere solo offerte di lavoro inserisci quanto segue:

    Status:JOB_STATE
    

    Sostituisci JOB_STATE con un stato del job: per esempio, FAILED.

gcloud

Visualizza tutti i job

Per visualizzare un elenco di job nel progetto corrente utilizzando il comando gcloud CLI, utilizza Comando gcloud batch jobs list.

gcloud batch jobs list

Visualizza un elenco filtrato di job

Facoltativamente, puoi aggiungere uno o più flag per visualizzare un elenco filtrato di job:

  • Per visualizzare solo le offerte di lavoro in una località specifica, includi il flag --location.

  • Per visualizzare solo i job in base a un'espressione di filtro, specifica la --filter flag.

Ad esempio, utilizza il seguente comando:

gcloud batch jobs list \
    --location=LOCATION \
    --filter="FILTER_EXPRESSION"

Sostituisci quanto segue:

  • LOCATION: la località in cui esistono uno o più job.

  • FILTER_EXPRESSION: un espressione di filtro che definisce i job che vuoi elencare. L'espressione di filtro deve definirne uno o più coppie proprietà-valore separate da zero o più Operatori booleani (AND, OR e NOT).

    Ad esempio, vedi le seguenti espressioni di filtro:

    • Filtra in base allo stato del job: per visualizzare solo i job che si trovano in una stato specifico, utilizza la seguente espressione di filtro:

      status.state="JOB_STATE"
      

      Sostituisci JOB_STATE con un stato del job: per esempio, FAILED.

    • Filtra in base alle etichette: Supponiamo che il tuo progetto abbia definito il seguente etichette:

      • Per indicare le posizioni di lavoro e le relative risorse create dalla tua ricerca team quando visualizzi i report di fatturazione Cloud, alcuni dei tuoi job le relative risorse hanno un'etichetta team impostata su research.

      • Per indicare carichi di lavoro sensibili al tempo, alcuni job hanno un valore deadline dell'etichetta, che è impostata su vari valori.

      • per indicare gli elementi eseguibili che il tuo team di sviluppo ha correttamente. testati, alcuni elementi eseguibili hanno un'etichetta tested impostata su true.

      Successivamente, puoi specificare la seguente espressione di filtro:

      (allocationPolicy.labels.team=research) AND ((labels.deadline:*) OR (runnables.labels.tested=true))
      

      Questa espressione di filtro elenca solo i job che soddisfano tutti i seguenti criteri di classificazione:

      • Job provenienti dal team di ricerca, che hanno un'etichetta team nella criterio di allocazione del job impostato su research.

      • Job che soddisfano almeno uno dei seguenti criteri:

        • Job sensibili al tempo, che hanno un'etichetta deadline nella job impostato su qualsiasi valore.

        • Job con almeno un eseguibile che è stato eseguito correttamente testati, ovvero job per i quali almeno uno è eseguibile Etichetta tested impostata su true.

API

Visualizza tutti i job

Per visualizzare un elenco di job nel progetto corrente per una località specifica utilizzando l'API Batch, effettua una richiesta GET Metodo jobs.list.

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs

Sostituisci quanto segue:

  • PROJECT_ID: il valore ID progetto del progetto attuale.

  • LOCATION: la località in cui esistono i job.

Visualizza un elenco filtrato di job

Facoltativamente, puoi specificare il parametro di query filter per visualizzare un di job in base a un'espressione di filtro.

Ad esempio, effettua la seguente richiesta GET:

GET https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?filter=FILTER_EXPRESSION

Sostituisci FILTER_EXPRESSION con un espressione di filtro che utilizza la codifica degli URL. L'espressione di filtro deve definire una o più coppie proprietà-valore che siano separati da zero o più Operatori booleani (AND, OR e NOT).

Ad esempio, vedi le seguenti espressioni di filtro:

  • Filtra in base allo stato del job: per visualizzare solo i job che si trovano in una stato specifico, utilizza la seguente espressione di filtro:

    status.state="JOB_STATE"
    

    Sostituisci JOB_STATE con un stato del job: per esempio, FAILED.

  • Filtra in base alle etichette: Supponiamo che il tuo progetto abbia definito il seguente etichette:

    • Per indicare le posizioni di lavoro e le relative risorse create dalla tua ricerca team quando visualizzi i report di fatturazione Cloud, alcuni dei tuoi job le relative risorse hanno un'etichetta team impostata su research.

    • Per indicare carichi di lavoro sensibili al tempo, alcuni job hanno un valore deadline dell'etichetta, che è impostata su vari valori.

    • per indicare gli elementi eseguibili che il tuo team di sviluppo ha correttamente. testati, alcuni elementi eseguibili hanno un'etichetta tested impostata su true.

    Successivamente, puoi specificare la seguente espressione di filtro:

    (allocationPolicy.labels.team%3Dresearch)%20AND%20((labels.deadline%3A*)%20OR%20(runnables.labels.tested%3Dtrue))
    

    Questa espressione di filtro elenca solo i job che soddisfano tutti i seguenti criteri di classificazione:

    • Job provenienti dal team di ricerca, che hanno un'etichetta team nella criterio di allocazione del job impostato su research.

    • Job che soddisfano almeno uno dei seguenti criteri:

      • Job sensibili al tempo, che hanno un'etichetta deadline nella job impostato su qualsiasi valore.

      • Job con almeno un eseguibile che è stato eseguito correttamente testati, ovvero job per i quali almeno uno è eseguibile Etichetta tested impostata su true.

Vai

Go

Per ulteriori informazioni, consulta API Go Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	"google.golang.org/api/iterator"
)

// Lists all jobs in the given project and region
func listJobs(w io.Writer, projectID, region string) error {
	// projectID := "your_project_id"
	// region := "us-central1"

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

	req := &batchpb.ListJobsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, region),
	}

	var jobs []*batchpb.Job
	it := batchClient.ListJobs(ctx, req)

	for {
		job, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("unable to list jobs: %w", err)
		}
		jobs = append(jobs, job)
	}

	fmt.Fprintf(w, "Jobs: %v\n", jobs)

	return nil
}

Java

Java

Per ulteriori informazioni, consulta API Java Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Job;
import java.io.IOException;

public class ListJobs {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region hosting the jobs.
    String region = "europe-central2";

    listJobs(projectId, region);
  }

  // Get a list of all jobs defined in given region.
  public static void listJobs(String projectId, String region) 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 `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Construct the parent path of the job.
      String parent = String.format("projects/%s/locations/%s", projectId, region);

      for (Job job : batchServiceClient.listJobs(parent).iterateAll()) {
        System.out.println(job.getName());
      }
      System.out.println("Listed all batch jobs.");
    }
  }
}

Node.js

Node.js

Per ulteriori informazioni, consulta API Node.js Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callListJobs() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${region}`,
  };

  // Run request
  const iterable = await batchClient.listJobsAsync(request);
  for await (const response of iterable) {
    console.log(response);
  }
}

callListJobs();

Python

Python

Per ulteriori informazioni, consulta API Python Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import batch_v1


def list_jobs(project_id: str, region: str) -> Iterable[batch_v1.Job]:
    """
    Get a list of all jobs defined in given region.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosting the jobs.

    Returns:
        An iterable collection of Job object.
    """
    client = batch_v1.BatchServiceClient()

    return client.list_jobs(parent=f"projects/{project_id}/locations/{region}")

C++

C++

Per ulteriori informazioni, consulta API C++ Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id) {
    auto const parent = "projects/" + project_id + "/locations/" + location_id;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    int i = 0;
    for (auto job : client.ListJobs(parent)) {
      if (!job) throw std::move(job).status();
      std::cout << "Job[" << i++ << "]  " << job->DebugString() << "\n";
    }
  }

Visualizzare i dettagli di un job

Puoi visualizzare i dettagli di un job nel progetto corrente utilizzando console Google Cloud, gcloud CLI, API Batch, Go, Java, Node.js, Python o C++.

Console

Per visualizzare i dettagli di un job nel progetto corrente utilizzando il nella console Google Cloud, segui questi passaggi:

  1. Nella console Google Cloud, vai alla pagina Elenco job.

    Vai all'elenco dei job

  2. Nella colonna Nome job, fai clic sul nome di un job.

    Si apre la pagina Dettagli job.

    La scheda Dettagli è aperta per impostazione predefinita. Per ulteriori informazioni, fai clic su altre schede.

gcloud

Per visualizzare i dettagli di un job nel progetto corrente utilizzando il gcloud CLI, utilizza Comando gcloud batch jobs describe con il flag --location.

gcloud batch jobs describe JOB_NAME \
    --location=LOCATION

Sostituisci quanto segue:

  • JOB_NAME: il nome di un job esistente.

  • LOCATION: la località in cui esiste il job.

API

Per visualizzare i dettagli di un job nel progetto corrente utilizzando il API Batch, effettua una richiesta GET all'API Metodo jobs.get.

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs/JOB_NAME

Sostituisci quanto segue:

  • PROJECT_ID: il valore ID progetto del progetto attuale.

  • LOCATION: la località in cui esiste il job.

  • JOB_NAME: il nome di un job esistente.

Vai

Go

Per ulteriori informazioni, consulta API Go Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
)

// Retrieves the information about the specified job, most importantly its status
func getJob(w io.Writer, projectID, region, jobName string) (*batchpb.Job, error) {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"

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

	req := &batchpb.GetJobRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s", projectID, region, jobName),
	}

	response, err := batchClient.GetJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to get job: %w", err)
	}

	fmt.Fprintf(w, "Job info: %v\n", response)

	return response, nil
}

Java

Java

Per ulteriori informazioni, consulta API Java Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.JobName;
import java.io.IOException;

public class GetJob {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region hosts the job.
    String region = "europe-central2";

    // The name of the job you want to retrieve information about.
    String jobName = "JOB_NAME";

    getJob(projectId, region, jobName);
  }

  // Retrieve information about a Batch Job.
  public static void getJob(String projectId, String region, String jobName) 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 `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      Job job =
          batchServiceClient.getJob(
              JobName.newBuilder()
                  .setProject(projectId)
                  .setLocation(region)
                  .setJob(jobName)
                  .build());

      System.out.printf("Retrieved the job: %s ", job.getName());
    }
  }
}

Node.js

Node.js

Per ulteriori informazioni, consulta API Node.js Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';
/**
 * The name of the job you want to retrieve information about.
 */
// const jobName = 'YOUR_JOB_NAME';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callGetJob() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${region}/jobs/${jobName}`,
  };

  // Run request
  const response = await batchClient.getJob(request);
  console.log(response);
}

callGetJob();

Python

Python

Per ulteriori informazioni, consulta API Python Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.


from google.cloud import batch_v1


def get_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    Retrieve information about a Batch Job.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosts the job.
        job_name: the name of the job you want to retrieve information about.

    Returns:
        A Job object representing the specified job.
    """
    client = batch_v1.BatchServiceClient()

    return client.get_job(
        name=f"projects/{project_id}/locations/{region}/jobs/{job_name}"
    )

C++

C++

Per ulteriori informazioni, consulta API C++ Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id) {
    auto const name = "projects/" + project_id + "/locations/" + location_id +
                      "/jobs/" + job_id;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.GetJob(name);
    if (!response) throw std::move(response).status();
    std::cout << "GetJob() succeeded with " << response->DebugString() << "\n";
  }

Visualizza le attività

Per visualizzare le attività per uno dei tuoi job, seleziona uno dei seguenti metodi:

Visualizza un elenco delle attività di un lavoro

Puoi visualizzare un elenco delle attività in un job o nel gruppo di attività di un job utilizzando il console Google Cloud, gcloud CLI, API Batch, Go, Java, Node.js, Python o C++.

Se vuoi filtrare un elenco di attività in un job o in un gruppo di attività di un job, ad esempio Ad esempio, per elencare solo le attività che sono state in esecuzione, devi utilizzare gcloud CLI o Batch API.

Console

Per visualizzare un riepilogo delle attività di un lavoro utilizzando il Console Google Cloud, visualizza i dettagli di un job per apri la pagina Dettagli job. Quindi, consulta la sezione Dettagli attività.

gcloud

Per visualizzare un elenco delle attività nel gruppo di attività di un job utilizzando la gcloud CLI, utilizza Comando gcloud batch tasks list con i seguenti flag:

gcloud batch tasks list \
    --job=JOB_NAME \
    --location=LOCATION

Sostituisci quanto segue:

  • JOB_NAME: il nome di un job esistente.

  • LOCATION: la località in cui se il job esiste.

Se vuoi, puoi aggiungere il flag --filter per visualizzare un elenco filtrato di attività in un gruppo di attività di un job in base a un'espressione di filtro.

Ad esempio, utilizza il seguente comando:

gcloud batch tasks list \
    --job=example-job \
    --location=us-central1 \
    --filter="FILTER_EXPRESSION"

Sostituisci FILTER_EXPRESSION con un espressione di filtro.

Ad esempio, puoi specificare la seguente espressione di filtro per visualizzare solo le attività di un gruppo di attività di un job che sono in esecuzione esecuzione terminata correttamente:

STATE=RUNNING OR STATE=SUCCEEDED

API

Per visualizzare un elenco di attività in un gruppo attività di un job utilizzando la API Batch, effettua una richiesta GET all'API Metodo tasks.list:

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs/JOB_NAME/taskGroups/TASK_GROUP_NAME/tasks

Sostituisci quanto segue:

  • PROJECT_ID: il valore ID progetto del progetto attuale.

  • LOCATION: la località in cui esiste il job.

  • JOB_NAME: il nome di un job esistente.

  • TASK_GROUP_NAME: il nome del gruppo attività che di cui vuoi visualizzare i dettagli. Il valore deve essere impostato su group0.

Se vuoi, puoi specificare il parametro di query filter per visualizzare un di attività in un gruppo di attività di un job in base a un'espressione di filtro.

Ad esempio, effettua la seguente richiesta GET:

GET https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs/example-job/taskGroups/group0/tasks?filter=FILTER_EXPRESSION

Sostituisci FILTER_EXPRESSION con un espressione di filtro che utilizza Codifica degli URL:

Ad esempio, puoi specificare la seguente espressione di filtro per visualizzare solo le attività di un gruppo di attività di un job che sono in esecuzione esecuzione terminata correttamente:

STATE=RUNNING%20OR%20STATE=SUCCEEDED

Tieni presente che l'espressione di filtro con codifica URL rappresenta la seguente decodifica espressione di filtro:

STATE=RUNNING OR STATE=SUCCEEDED

Vai

Go

Per ulteriori informazioni, consulta API Go Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	"google.golang.org/api/iterator"
)

// Lists all tasks in the given project and region
func listTasks(w io.Writer, projectID, region, jobName, taskGroup string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"
	// taskGroup := "group0" // defaults to "group0" on job creation unless overridden

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

	req := &batchpb.ListTasksRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/jobs/%s/taskGroups/%s", projectID, region, jobName, taskGroup),
	}

	var tasks []*batchpb.Task
	it := batchClient.ListTasks(ctx, req)

	for {
		task, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("unable to list tasks: %w", err)
		}
		tasks = append(tasks, task)
	}

	fmt.Fprintf(w, "Tasks: %v\n", tasks)

	return nil
}

Java

Java

Per ulteriori informazioni, consulta API Java Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Task;
import java.io.IOException;

public class ListTasks {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region hosts the job.
    String region = "europe-central2";
    // Name of the job which tasks you want to list.
    String jobName = "JOB_NAME";
    // Name of the group of tasks. Usually it's `group0`.
    String groupName = "group0";

    listTasks(projectId, region, jobName, groupName);
  }

  // Get a list of all jobs defined in given region.
  public static void listTasks(String projectId, String region, String jobName, String groupName)
      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 `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      String parent = String.format("projects/%s/locations/%s/jobs/%s/taskGroups/%s", projectId,
          region, jobName, groupName);
      for (Task task : batchServiceClient.listTasks(parent).iterateAll()) {
        System.out.println(task.getName());
      }
    }
  }
}

Node.js

Node.js

Per ulteriori informazioni, consulta API Node.js Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';
/**
 * The name of the job which tasks you want to list.
 */
// const jobName = 'YOUR_JOB_NAME';
/**
 * The name of the group of tasks. Usually it's `group0`.
 */
// const groupName = 'group0';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callListTasks() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${region}/jobs/${jobName}/taskGroups/${groupName}`,
  };

  // Run request
  const iterable = await batchClient.listTasksAsync(request);
  for await (const response of iterable) {
    console.log(response);
  }
}

callListTasks();

Python

Python

Per ulteriori informazioni, consulta API Python Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import batch_v1


def list_tasks(
    project_id: str, region: str, job_name: str, group_name: str
) -> Iterable[batch_v1.Task]:
    """
    Get a list of all jobs defined in given region.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosting the jobs.
        job_name: name of the job which tasks you want to list.
        group_name: name of the group of tasks. Usually it's `group0`.

    Returns:
        An iterable collection of Task objects.
    """
    client = batch_v1.BatchServiceClient()

    return client.list_tasks(
        parent=f"projects/{project_id}/locations/{region}/jobs/{job_name}/taskGroups/{group_name}"
    )

C++

C++

Per ulteriori informazioni, consulta API C++ Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id, std::string const& group_id) {
    auto const parent = "projects/" + project_id + "/locations/" + location_id +
                        "/jobs/" + job_id + "/taskGroups/" + group_id;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    int i = 0;
    for (auto task : client.ListTasks(parent)) {
      if (!task) throw std::move(task).status();
      std::cout << "Task[" << i++ << "]  " << task->DebugString() << "\n";
    }
  }

Visualizzare i dettagli di un'attività

Puoi visualizzare i dettagli di un'attività utilizzando il console Google Cloud, gcloud CLI, API Batch, Go, Java, Node.js, Python o C++.

Console

Per visualizzare i dettagli di un'attività utilizzando il Console Google Cloud, visualizza i dettagli di un job per apri la pagina Dettagli job. Quindi, consulta la sezione Dettagli attività.

gcloud

Per visualizzare i dettagli di un'attività con gcloud CLI, utilizza Comando gcloud batch tasks describe con i seguenti flag:

gcloud batch tasks describe TASK_INDEX \
  --location=LOCATION \
  --job=JOB_NAME \
  --task_group=TASK_GROUP_NAME

Sostituisci quanto segue:

  • TASK_INDEX: l'indice dell'attività che vuoi visualizzare i dettagli. In un gruppo di attività, l'indice delle attività inizia da 0 per la prima dell'attività e aumenta di 1 a ogni attività aggiuntiva. Ad esempio, un'attività gruppo che contiene quattro attività ha gli indici 0, 1, 2 e 3.

  • TASK_GROUP_NAME: il nome del gruppo di attività che contiene l'attività di cui vuoi visualizzare i dettagli. Il valore deve essere impostato su group0.

  • JOB_NAME: il nome di un job esistente.

  • LOCATION: la località in cui se il job esiste.

API

Per visualizzare i dettagli di un'attività utilizzando l'API Batch, crea un Richiesta di GET inviata a Metodo tasks.get:

GET https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs/JOB_NAME/taskGroups/TASK_GROUP_NAME/tasks/TASK_INDEX

Sostituisci quanto segue:

  • PROJECT_ID: il valore ID progetto del progetto attuale.

  • LOCATION: la località in cui esiste il job.

  • JOB_NAME: il nome di un job esistente.

  • TASK_GROUP_NAME: il nome del gruppo di attività che contiene l'attività di cui vuoi visualizzare i dettagli. Il valore deve essere impostato su group0.

  • TASK_INDEX: l'indice dell'attività che ti interessa di cui vedere i dettagli. In un gruppo di attività, l'indice delle attività inizia da 0 per alla prima attività e aumenta di 1 con ogni attività aggiuntiva. Ad esempio: un gruppo di attività contenente quattro attività ha gli indici 0, 1, 2, un, 3.

Vai

Go

Per ulteriori informazioni, consulta API Go Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
)

// Retrieves the information about the specified job, most importantly its status
func getTask(w io.Writer, projectID, region, jobName, taskGroup string, taskNumber int32) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"
	// taskGroup := "group0" // defaults to "group0" on job creation unless overridden
	// taskNumber := 0

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

	req := &batchpb.GetTaskRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s/taskGroups/%s/tasks/%d",
			projectID, region, jobName, taskGroup, taskNumber),
	}

	response, err := batchClient.GetTask(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get task: %w", err)
	}

	fmt.Fprintf(w, "Task info: %v\n", response)

	return nil
}

Java

Java

Per ulteriori informazioni, consulta API Java Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.Task;
import com.google.cloud.batch.v1.TaskName;
import java.io.IOException;

public class GetTask {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region hosts the job.
    String region = "europe-central2";
    // The name of the job you want to retrieve information about.
    String jobName = "JOB_NAME";
    // The name of the group that owns the task you want to check. Usually it's `group0`.
    String groupName = "group0";
    // Number of the task you want to look up.
    int taskNumber = 0;

    getTask(projectId, region, jobName, groupName, taskNumber);
  }

  // Retrieve information about a Task.
  public static void getTask(String projectId, String region, String jobName, String groupName,
      int taskNumber) 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 `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      Task task = batchServiceClient.getTask(TaskName.newBuilder()
          .setProject(projectId)
          .setLocation(region)
          .setJob(jobName)
          .setTaskGroup(groupName)
          .setTask(String.valueOf(taskNumber))
          .build());
      System.out.printf("Retrieved task information: %s", task.getName());
    }
  }
}

Node.js

Node.js

Per ulteriori informazioni, consulta API Node.js Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region that hosts the job.
 */
// const region = 'us-central-1';
/**
 * The name of the job you want to retrieve information about.
 */
// const jobName = 'YOUR_JOB_NAME';
/**
 * The name of the group that owns the task you want to check.
 * Usually it's `group0`.
 */
// const groupName = 'group0';
/**
 * The number of the task you want to look up.
 */
// const taskNumber = 0;

// Imports the Batch library
const batchLib = require('@google-cloud/batch');

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

async function callGetJob() {
  // Construct request
  const request = {
    name:
      `projects/${projectId}/locations/${region}/jobs/${jobName}` +
      `/taskGroups/${groupName}/tasks/${taskNumber}`,
  };

  // Run request
  const response = await batchClient.getTask(request);
  console.log(response);
}

callGetJob();

Python

Python

Per ulteriori informazioni, consulta API Python Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.


from google.cloud import batch_v1


def get_task(
    project_id: str, region: str, job_name: str, group_name: str, task_number: int
) -> batch_v1.Task:
    """
    Retrieve information about a Task.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region hosts the job.
        job_name: the name of the job you want to retrieve information about.
        group_name: the name of the group that owns the task you want to check. Usually it's `group0`.
        task_number: number of the task you want to look up.

    Returns:
        A Task object representing the specified task.
    """
    client = batch_v1.BatchServiceClient()

    return client.get_task(
        name=f"projects/{project_id}/locations/{region}/jobs/{job_name}"
        f"/taskGroups/{group_name}/tasks/{task_number}"
    )

C++

C++

Per ulteriori informazioni, consulta API C++ Batch documentazione di riferimento.

Per eseguire l'autenticazione in modalità batch, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id, std::string const& group_id,
     std::string const& task_number) {
    auto const name = "projects/" + project_id + "/locations/" + location_id +
                      "/jobs/" + job_id + "/taskGroups/" + group_id +
                      "/tasks/" + task_number;
    // Initialize a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.GetTask(name);
    if (!response) throw std::move(response).status();
    std::cout << "GetTask() succeeded with " << response->DebugString() << "\n";
  }

Passaggi successivi