작업 및 태스크 보기

이 문서에서는 일괄 작업 및 태스크를 보는 방법을 설명합니다.

시작하기 전에

  • Batch를 사용한 적이 없으면 Batch 시작하기를 검토하고 프로젝트 및 사용자 기본 요건을 완료하여 Batch를 사용 설정하세요.
  • 작업 및 태스크를 보는 데 필요한 권한을 얻으려면 프로젝트에 대한 Batch 작업 뷰어(roles/batch.jobsViewer) 또는 Batch 작업 편집자(roles/batch.jobsEditor) IAM 역할을 부여해 달라고 관리자에게 요청하세요. 역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

    커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

작업 보기

작업을 보려면 다음 방법 중 하나를 선택합니다.

작업 목록 보기

Google Cloud 콘솔, gcloud CLI, Batch API, Go, 자바, Node.js, Python 또는 C++를 사용하여 현재 프로젝트의 작업 목록을 볼 수 있습니다.

콘솔

  1. Google Cloud 콘솔을 사용하여 현재 프로젝트의 작업 목록을 보려면 작업 목록 페이지로 이동합니다.

    작업 목록으로 이동

    작업 목록은 페이지가 여러 개일 수 있습니다. 다음 페이지로 계속 진행해야 하는 경우 화면 하단에서 다음을 클릭하세요.

  2. (선택사항) 작업 목록을 필터링하려면 필터를 클릭합니다. 그런 다음 속성 및 값을 입력하거나 선택합니다.

    예를 들어 특정 상태의 작업만 포함하도록 목록을 필터링하려면 다음을 입력합니다.

    Status:JOB_STATE
    

    JOB_STATE작업 상태(예: FAILED)로 바꿉니다.

gcloud

모든 작업 보기

gcloud CLI를 사용하여 현재 프로젝트의 작업 목록을 보려면 gcloud batch jobs list 명령어를 사용합니다.

gcloud batch jobs list

필터링된 작업 목록 보기

필요한 경우 하나 이상의 플래그를 추가하여 필터링된 작업 목록을 볼 수 있습니다.

  • 특정 위치의 작업만 보려면 --location 플래그를 포함합니다.

  • 필터 표현식을 기준으로 작업만 보려면 --filter 플래그를 지정합니다.

예를 들어 다음 명령어를 사용합니다.

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

다음을 바꿉니다.

  • LOCATION: 하나 이상의 작업이 있는 위치

  • FILTER_EXPRESSION: 나열할 작업을 정의하는 필터 표현식. 필터 표현식은 0개 이상의 불리언 연산자(AND, OR, NOT)로 구분된 하나 이상의 속성-값 쌍을 정의해야 합니다.

    예를 들어 다음 필터 표현식을 참조하세요.

    • 작업 상태를 기준으로 필터링: 특정 상태의 작업만 보려면 다음 필터 표현식을 사용합니다.

      status.state="JOB_STATE"
      

      JOB_STATE작업 상태(예: FAILED)로 바꿉니다.

    • 라벨 기준 필터링: 프로젝트에서 다음 커스텀 라벨을 정의했다고 가정합니다.

      • Cloud Billing 보고서를 볼 때 리서치팀에서 만든 작업과 해당 리소스를 표시하기 위해 일부 작업 및 해당 리소스에는 research로 설정된 team 라벨이 있습니다.

      • 시간에 민감한 워크로드를 표시하기 위해 일부 작업에는 다양한 값으로 설정된 deadline 라벨이 있습니다.

      • 개발팀이 성공적으로 테스트한 실행 가능 항목을 나타내기 위해 일부 실행 가능 항목에는 true로 설정된 tested 라벨이 있습니다.

      그런 다음, 다음 필터 표현식을 지정할 수 있습니다.

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

      이 필터 표현식은 다음 기준을 모두 충족하는 작업만 나열합니다.

      • research로 설정된 작업 할당 정책에 team 라벨이 있는 리서치팀의 작업입니다.

      • 다음 기준 중 하나 이상을 충족하는 작업:

        • 임의의 값으로 설정된 작업에 deadline 라벨이 있는 시간에 민감한 작업

        • 성공적으로 테스트된 실행 가능한 항목이 하나 이상 있는 작업, 즉 true로 설정된 tested 라벨을 사용한 실행 가능한 항목이 하나 이상 있는 작업

API

모든 작업 보기

Batch API를 사용하여 특정 위치의 현재 프로젝트에 있는 작업 목록을 보려면 jobs.list 메서드에 대해 GET 요청을 실행합니다.

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

다음을 바꿉니다.

필터링된 작업 목록 보기

필요한 경우 필터 표현식에 따라 필터링된 작업 목록을 보기 위해 filter 쿼리 매개변수를 지정할 수 있습니다.

예를 들어 다음 GET 요청을 수행합니다.

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

FILTER_EXPRESSIONURL 인코딩을 사용하는 필터 표현식으로 바꿉니다. 필터 표현식은 0개 이상의 불리언 연산자(AND, OR, NOT)로 구분된 하나 이상의 속성-값 쌍을 정의해야 합니다.

예를 들어 다음 필터 표현식을 참조하세요.

  • 작업 상태를 기준으로 필터링: 특정 상태의 작업만 보려면 다음 필터 표현식을 사용합니다.

    status.state="JOB_STATE"
    

    JOB_STATE작업 상태(예: FAILED)로 바꿉니다.

  • 라벨 기준 필터링: 프로젝트에서 다음 커스텀 라벨을 정의했다고 가정합니다.

    • Cloud Billing 보고서를 볼 때 리서치팀에서 만든 작업과 해당 리소스를 표시하기 위해 일부 작업 및 해당 리소스에는 research로 설정된 team 라벨이 있습니다.

    • 시간에 민감한 워크로드를 표시하기 위해 일부 작업에는 다양한 값으로 설정된 deadline 라벨이 있습니다.

    • 개발팀이 성공적으로 테스트한 실행 가능 항목을 나타내기 위해 일부 실행 가능 항목에는 true로 설정된 tested 라벨이 있습니다.

    그런 다음, 다음 필터 표현식을 지정할 수 있습니다.

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

    이 필터 표현식은 다음 기준을 모두 충족하는 작업만 나열합니다.

    • research로 설정된 작업 할당 정책에 team 라벨이 있는 리서치팀의 작업입니다.

    • 다음 기준 중 하나 이상을 충족하는 작업:

      • 임의의 값으로 설정된 작업에 deadline 라벨이 있는 시간에 민감한 작업

      • 성공적으로 테스트된 실행 가능한 항목이 하나 이상 있는 작업, 즉 true로 설정된 tested 라벨을 사용한 실행 가능한 항목이 하나 이상 있는 작업

Go

Go

자세한 내용은 Batch Go API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Java API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Node.js API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Python API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch C++ API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

작업 세부정보 보기

Google Cloud 콘솔, gcloud CLI, Batch API, Go, 자바, Node.js, Python, C++를 사용하여 현재 프로젝트의 작업 세부정보를 볼 수 있습니다.

콘솔

Google Cloud 콘솔을 사용하여 현재 프로젝트의 작업 세부정보를 보려면 다음 단계를 따르세요.

  1. Google Cloud 콘솔에서 작업 목록 페이지로 이동합니다.

    작업 목록으로 이동

  2. 작업 이름 열에서 작업 이름을 클릭합니다.

    작업 세부정보 페이지가 열립니다.

    세부정보 탭이 기본적으로 열립니다. 자세한 내용을 보려면 다른 탭을 클릭하세요.

gcloud

gcloud CLI를 사용하여 현재 프로젝트의 작업 세부정보를 보려면 --location 플래그와 함께 gcloud batch jobs describe 명령어를 사용합니다.

gcloud batch jobs describe JOB_NAME \
    --location=LOCATION

다음을 바꿉니다.

  • JOB_NAME: 기존 작업의 이름입니다.

  • LOCATION: 작업이 있는 위치입니다.

API

Batch API를 사용하여 현재 프로젝트의 작업 세부정보를 보려면 jobs.get 메서드GET 요청을 수행합니다.

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

다음을 바꿉니다.

  • PROJECT_ID: 현재 프로젝트의 프로젝트 ID입니다.

  • LOCATION: 작업이 있는 위치입니다.

  • JOB_NAME: 기존 작업의 이름입니다.

Go

Go

자세한 내용은 Batch Go API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Java API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Node.js API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Python API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

자세한 내용은 Batch C++ API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

할 일 보기

작업 중 하나의 태스크를 보려면 다음 방법 중 하나를 선택합니다.

작업 태스크 목록 보기

Google Cloud 콘솔, gcloud CLI, Batch API, Go, 자바, Node.js, Python, C++를 사용하여 작업 또는 작업의 태스크 그룹에서 태스크 목록을 볼 수 있습니다.

작업 또는 작업의 태스크 그룹에 있는 태스크 목록을 필터링하려면(예: 실행이 완료된 작업만 나열) gcloud CLI 또는 Batch API를 사용해야 합니다.

콘솔

Google Cloud 콘솔을 사용하여 작업의 태스크 요약을 보려면 작업 세부정보를 확인하여 작업 세부정보 페이지를 엽니다. 그런 다음 태스크 세부정보 섹션을 참조하세요.

gcloud

gcloud CLI를 사용하여 작업 태스크 그룹의 태스크 목록을 보려면 다음 플래그와 함께 gcloud batch tasks list 명령어를 사용합니다.

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

다음을 바꿉니다.

  • JOB_NAME: 기존 작업의 이름입니다.

  • LOCATION: 작업이 있는 위치입니다.

원하는 경우 --filter 플래그를 추가하여 필터 표현식을 기준으로 작업의 태스크 그룹에 있는 필터링된 태스크 목록을 확인할 수 있습니다.

예를 들어 다음 명령어를 사용합니다.

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

FILTER_EXPRESSION필터 표현식으로 바꿉니다.

예를 들어 실행 중이거나 실행을 성공적으로 마친 작업의 태스크 그룹에 있는 태스크만 표시하도록 다음 필터 표현식을 지정할 수 있습니다.

STATE=RUNNING OR STATE=SUCCEEDED

API

Batch API를 사용하여 작업의 태스크 그룹에 있는 태스크 목록을 보려면 tasks.list 메서드에 대한GET 요청을 수행합니다.

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

다음을 바꿉니다.

  • PROJECT_ID: 현재 프로젝트의 프로젝트 ID입니다.

  • LOCATION: 작업이 있는 위치입니다.

  • JOB_NAME: 기존 작업의 이름입니다.

  • TASK_GROUP_NAME: 세부정보를 보려는 태스크 그룹의 이름입니다. 값을 group0으로 설정해야 합니다.

원하는 경우 필터 표현식에 따라 작업의 태스크 그룹에 있는 필터링된 태스크 목록을 보기 위해 filter 쿼리 매개변수를 지정할 수 있습니다.

예를 들어 다음 GET 요청을 수행합니다.

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

FILTER_EXPRESSIONURL 인코딩을 사용하는 필터 표현식으로 바꿉니다.

예를 들어 실행 중이거나 실행을 성공적으로 마친 작업의 태스크 그룹에 있는 태스크만 표시하도록 다음 필터 표현식을 지정할 수 있습니다.

STATE=RUNNING%20OR%20STATE=SUCCEEDED

URL로 인코딩된 필터 표현식은 다음 디코딩된 필터 표현식을 나타냅니다.

STATE=RUNNING OR STATE=SUCCEEDED

Go

Go

자세한 내용은 Batch Go API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Java API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Node.js API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Python API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch C++ API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

태스크 세부정보 보기

Google Cloud 콘솔, gcloud CLI, Batch API, Go, 자바, Node.js, Python, C++를 사용하여 태스크의 세부정보를 볼 수 있습니다.

콘솔

Google Cloud 콘솔을 사용하여 태스크의 세부정보를 보려면 작업 세부정보를 보고 작업 세부정보 페이지를 엽니다. 그런 다음 태스크 세부정보 섹션을 참조하세요.

gcloud

gcloud CLI를 사용하여 태스크의 세부정보를 보려면 다음 플래그와 함께 gcloud batch tasks describe 명령어를 사용합니다.

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

다음을 바꿉니다.

  • TASK_INDEX: 세부정보를 보려는 태스크의 색인입니다. 태스크 그룹의 태스크 색인은 첫 번째 태스크에서 0부터 시작하여 태스크를 추가할 때마다 1씩 증가합니다. 예를 들어 태스크 4개가 포함된 태스크 그룹의 색인은 0, 1, 2, 3입니다.

  • TASK_GROUP_NAME: 세부정보를 보려는 태스크가 포함된 태스크 그룹의 이름입니다. 값을 group0으로 설정해야 합니다.

  • JOB_NAME: 기존 작업의 이름입니다.

  • LOCATION: 작업이 있는 위치입니다.

API

Batch API를 사용하여 태스크의 세부정보를 보려면 tasks.get 메서드에 대해 GET 요청을 수행합니다.

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

다음을 바꿉니다.

  • PROJECT_ID: 현재 프로젝트의 프로젝트 ID입니다.

  • LOCATION: 작업이 있는 위치입니다.

  • JOB_NAME: 기존 작업의 이름입니다.

  • TASK_GROUP_NAME: 세부정보를 보려는 태스크가 포함된 태스크 그룹의 이름입니다. 값을 group0으로 설정해야 합니다.

  • TASK_INDEX: 세부정보를 보려는 태스크의 색인입니다. 태스크 그룹의 태스크 색인은 첫 번째 태스크에서 0부터 시작하여 태스크를 추가할 때마다 1씩 증가합니다. 예를 들어 태스크 4개가 포함된 태스크 그룹의 색인은 0, 1, 2, 3입니다.

Go

Go

자세한 내용은 Batch Go API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Java API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Node.js API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Batch Python API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

자세한 내용은 Batch C++ API 참조 문서를 확인하세요.

Batch에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

다음 단계