Afficher les tâches et les tâches

Ce document explique comment afficher les tâches et les jobs Batch.

Avant de commencer

Afficher vos offres d'emploi

Pour afficher vos tâches, sélectionnez l'une des méthodes suivantes:

Afficher une liste de vos jobs

Vous pouvez afficher la liste des tâches du projet en cours à l'aide de la console Google Cloud, de gcloud CLI, de l'API Batch, de Go, Java, Node.js, Python ou C++.

Console

  1. Pour afficher la liste des tâches du projet en cours à l'aide de la console Google Cloud, accédez à la page Liste des tâches.

    Accéder à la liste des jobs

    La liste des jobs peut comporter plusieurs pages. Si vous devez passer à la page suivante, cliquez sur Suivant en bas de l'écran.

  2. Facultatif: Si vous souhaitez filtrer la liste des tâches, cliquez sur Filtrer. Ensuite, saisissez ou sélectionnez une propriété et une valeur.

    Par exemple, pour filtrer la liste afin de n'inclure que les tâches dans un état spécifique, saisissez la commande suivante:

    Status:JOB_STATE
    

    Remplacez JOB_STATE par un état de la tâche, par exemple FAILED.

gcloud

Afficher toutes les tâches

Pour afficher la liste des tâches du projet en cours à l'aide de la gcloud CLI, exécutez la commande gcloud batch jobs list.

gcloud batch jobs list

Afficher une liste filtrée de jobs

Vous pouvez éventuellement ajouter un ou plusieurs indicateurs pour afficher une liste filtrée des tâches:

  • Pour n'afficher que les tâches d'un emplacement spécifique, incluez l'option --location.

  • Pour n'afficher que les tâches basées sur une expression de filtre, spécifiez l'option --filter.

Par exemple, exécutez la commande suivante :

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

Remplacez les éléments suivants :

  • LOCATION: emplacement où se trouvent une ou plusieurs offres d'emploi.

  • FILTER_EXPRESSION: expression de filtre qui définit les tâches que vous souhaitez répertorier. L'expression de filtre doit définir une ou plusieurs paires propriété-valeur séparées par zéro ou plusieurs opérateurs booléens (AND, OR et NOT).

    Vous pouvez par exemple consulter les expressions de filtre suivantes:

    • Filtrer en fonction de l'état de la tâche:pour n'afficher que les tâches dans un état spécifique, utilisez l'expression de filtre suivante:

      status.state="JOB_STATE"
      

      Remplacez JOB_STATE par un état de la tâche, par exemple FAILED.

    • Filtrer en fonction des étiquettes:supposons que votre projet ait défini les étiquettes personnalisées suivantes:

      • Pour indiquer les tâches et leurs ressources créées par votre équipe de recherche lorsque vous consultez des rapports Cloud Billing, certaines de vos tâches et leurs ressources possèdent un libellé team défini sur research.

      • Pour indiquer des charges de travail urgentes, certaines tâches comportent un libellé deadline, défini sur différentes valeurs.

      • Pour indiquer que votre équipe de développement a testé avec succès des exécutables, certains ont un libellé tested défini sur true.

      Vous pouvez ensuite spécifier l'expression de filtre suivante:

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

      Cette expression de filtre ne répertorie que les tâches qui répondent à tous les critères suivants:

      • Tâches issues de l'équipe de recherche, dont le libellé team est défini dans la règle d'allocation définie sur research

      • Emplois qui répondent à au moins l'un des critères suivants:

        • Les tâches urgentes, dont le libellé deadline est défini sur n'importe quelle valeur.

        • Les tâches comportant au moins un exécutable dont le test a réussi, c'est-à-dire les jobs dont au moins un exécutable avec un libellé tested défini sur true.

API

Afficher toutes les tâches

Pour afficher la liste des tâches du projet en cours pour un emplacement spécifique à l'aide de l'API Batch, envoyez une requête GET à la méthode jobs.list.

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

Remplacez les éléments suivants :

Afficher une liste filtrée de jobs

Vous pouvez éventuellement spécifier le paramètre de requête filter pour afficher une liste filtrée des tâches en fonction d'une expression de filtre.

Par exemple, exécutez la requête GET suivante:

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

Remplacez FILTER_EXPRESSION par une expression de filtre qui utilise l'encodage d'URL. L'expression de filtre doit définir une ou plusieurs paires propriété-valeur séparées par zéro ou plusieurs opérateurs booléens (AND, OR et NOT).

Vous pouvez par exemple consulter les expressions de filtre suivantes:

  • Filtrer en fonction de l'état de la tâche:pour n'afficher que les tâches dans un état spécifique, utilisez l'expression de filtre suivante:

    status.state="JOB_STATE"
    

    Remplacez JOB_STATE par un état de la tâche, par exemple FAILED.

  • Filtrer en fonction des étiquettes:supposons que votre projet ait défini les étiquettes personnalisées suivantes:

    • Pour indiquer les tâches et leurs ressources créées par votre équipe de recherche lorsque vous consultez des rapports Cloud Billing, certaines de vos tâches et leurs ressources possèdent un libellé team défini sur research.

    • Pour indiquer des charges de travail urgentes, certaines tâches comportent un libellé deadline, défini sur différentes valeurs.

    • Pour indiquer que votre équipe de développement a testé avec succès des exécutables, certains ont un libellé tested défini sur true.

    Vous pouvez ensuite spécifier l'expression de filtre suivante:

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

    Cette expression de filtre ne répertorie que les tâches qui répondent à tous les critères suivants:

    • Tâches issues de l'équipe de recherche, dont le libellé team est défini dans la règle d'allocation définie sur research

    • Emplois qui répondent à au moins l'un des critères suivants:

      • Les tâches urgentes, dont le libellé deadline est défini sur n'importe quelle valeur.

      • Les tâches comportant au moins un exécutable dont le test a réussi, c'est-à-dire les jobs dont au moins un exécutable avec un libellé tested défini sur true.

Go

Go

Pour en savoir plus, consultez la documentation de référence de l'API Batch Go.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Java.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Node.js.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * 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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Python.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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++

Pour en savoir plus, consultez la documentation de référence de l'API Batch C++.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

#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";
    }
  }

Afficher les détails d'un job

Vous pouvez afficher les détails d'une tâche dans le projet en cours à l'aide de la console Google Cloud, de gcloud CLI, de l'API Batch, de Go, Java, Node.js, Python ou C++.

Console

Pour afficher les détails d'une tâche dans le projet en cours à l'aide de la console Google Cloud, procédez comme suit:

  1. Dans la console Google Cloud, accédez à la page Liste des tâches.

    Accéder à la liste des jobs

  2. Dans la colonne Job name (Nom de la tâche), cliquez sur le nom d'une tâche.

    La page "Job Details" (informations sur le job) s'ouvre alors.

    L'onglet Détails est ouvert par défaut. Pour en savoir plus, cliquez sur "Autres onglets".

gcloud

Pour afficher les détails d'une tâche dans le projet en cours à l'aide de la gcloud CLI, exécutez la commande gcloud batch jobs describe avec l'option --location.

gcloud batch jobs describe JOB_NAME \
    --location=LOCATION

Remplacez les éléments suivants :

  • JOB_NAME: nom d'une tâche existante.

  • LOCATION: emplacement où se trouve la tâche.

API

Pour afficher les détails d'une tâche dans le projet en cours à l'aide de l'API Batch, envoyez une requête GET à la méthode jobs.get.

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

Remplacez les éléments suivants :

Go

Go

Pour en savoir plus, consultez la documentation de référence de l'API Batch Go.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Java.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Node.js.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * 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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Python.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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++

Pour en savoir plus, consultez la documentation de référence de l'API Batch C++.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

#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";
  }

Afficher les tâches

Pour afficher les tâches d'une de vos tâches, sélectionnez l'une des méthodes suivantes:

Afficher la liste des tâches d'une mission

Vous pouvez afficher la liste des tâches d'une tâche ou d'un groupe de tâches à l'aide de la console Google Cloud, de gcloud CLI, de l'API Batch, de Go, de Java, de Node.js, de Python ou de C++.

Si vous souhaitez filtrer une liste de tâches dans une tâche ou un groupe de tâches (par exemple, pour ne répertorier que les tâches dont l'exécution a réussi), vous devez utiliser la gcloud CLI ou l'API Batch.

Console

Pour afficher un résumé des tâches d'une tâche à l'aide de la console Google Cloud, affichez les détails d'une tâche pour ouvrir la page Informations sur la tâche. Consultez ensuite la section Détails de la tâche.

gcloud

Pour afficher la liste des tâches d'un groupe de tâches à l'aide de la gcloud CLI, exécutez la commande gcloud batch tasks list avec les options suivantes:

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

Remplacez les éléments suivants :

  • JOB_NAME: nom d'une tâche existante.

  • LOCATION: emplacement où se trouve le job.

Vous pouvez éventuellement ajouter l'option --filter pour afficher une liste filtrée des tâches d'un groupe de tâches d'une tâche en fonction d'une expression de filtre.

Par exemple, exécutez la commande suivante :

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

Remplacez FILTER_EXPRESSION par une expression de filtre.

Par exemple, vous pouvez spécifier l'expression de filtre suivante pour n'afficher que les tâches d'un groupe de tâches d'une tâche en cours d'exécution ou dont l'exécution a abouti:

STATE=RUNNING OR STATE=SUCCEEDED

API

Pour afficher la liste des tâches d'un groupe de tâches d'une tâche à l'aide de l'API Batch, envoyez une requête GET à la méthode tasks.list:

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

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet en cours

  • LOCATION: emplacement où se trouve la tâche.

  • JOB_NAME: nom d'une tâche existante.

  • TASK_GROUP_NAME: nom du groupe de tâches dont vous souhaitez afficher les détails. La valeur doit être définie sur group0.

Vous pouvez éventuellement spécifier le paramètre de requête filter pour afficher une liste filtrée des tâches d'un groupe de tâches d'une tâche en fonction d'une expression de filtre.

Par exemple, exécutez la requête GET suivante:

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

Remplacez FILTER_EXPRESSION par une expression de filtre qui utilise l'encodage d'URL.

Par exemple, vous pouvez spécifier l'expression de filtre suivante pour n'afficher que les tâches d'un groupe de tâches d'une tâche en cours d'exécution ou dont l'exécution a abouti:

STATE=RUNNING%20OR%20STATE=SUCCEEDED

Notez que l'expression de filtre encodée en URL représente l'expression de filtre décodée suivante:

STATE=RUNNING OR STATE=SUCCEEDED

Go

Go

Pour en savoir plus, consultez la documentation de référence de l'API Batch Go.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Java.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Node.js.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * 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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Python.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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++

Pour en savoir plus, consultez la documentation de référence de l'API Batch C++.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

#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";
    }
  }

Afficher les détails d'une tâche

Vous pouvez afficher les détails d'une tâche à l'aide de la console Google Cloud, de gcloud CLI, de l'API Batch, de Go, de Java, de Node.js, de Python ou de C++.

Console

Pour afficher les détails d'une tâche à l'aide de la console Google Cloud, affichez les détails d'une tâche pour ouvrir la page Informations sur la tâche. Consultez ensuite la section Détails de la tâche.

gcloud

Pour afficher les détails d'une tâche à l'aide de la gcloud CLI, exécutez la commande gcloud batch tasks describe avec les options suivantes:

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

Remplacez les éléments suivants :

  • TASK_INDEX: index de la tâche dont vous souhaitez afficher les détails. Dans un groupe de tâches, l'index de la tâche commence à 0 pour la première tâche et augmente de 1 à chaque tâche supplémentaire. Par exemple, un groupe de tâches contenant quatre tâches possède les index 0, 1, 2 et 3.

  • TASK_GROUP_NAME: nom du groupe de tâches qui contient la tâche dont vous souhaitez afficher les détails. La valeur doit être définie sur group0.

  • JOB_NAME: nom d'une tâche existante.

  • LOCATION: emplacement où se trouve le job.

API

Pour afficher les détails d'une tâche à l'aide de l'API Batch, envoyez une requête GET à la méthode tasks.get:

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

Remplacez les éléments suivants :

  • PROJECT_ID: ID du projet en cours

  • LOCATION: emplacement où se trouve la tâche.

  • JOB_NAME: nom d'une tâche existante.

  • TASK_GROUP_NAME: nom du groupe de tâches qui contient la tâche dont vous souhaitez afficher les détails. La valeur doit être définie sur group0.

  • TASK_INDEX: index de la tâche dont vous souhaitez afficher les détails. Dans un groupe de tâches, l'index de la tâche commence à 0 pour la première tâche et augmente de 1 à chaque tâche supplémentaire. Par exemple, un groupe de tâches contenant quatre tâches possède les index 0, 1, 2, 3.

Go

Go

Pour en savoir plus, consultez la documentation de référence de l'API Batch Go.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Java.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Node.js.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * 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

Pour en savoir plus, consultez la documentation de référence de l'API Batch Python.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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++

Pour en savoir plus, consultez la documentation de référence de l'API Batch C++.

Pour vous authentifier auprès de Batch, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

#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";
  }

Étapes suivantes