Membuat dan menjalankan tugas yang mengirim notifikasi status Pub/Sub

Dokumen ini menjelaskan cara membuat tugas Batch yang mengirim Pub/Sub notifikasi. Anda dapat menggunakan Pub/Sub untuk mendapatkan notifikasi saat status tugas atau tugas berubah, atau saat tugas atau tugas memasuki status tertentu. Untuk mengetahui informasi selengkapnya, lihat Memantau tugas menggunakan notifikasi.

Sebelum memulai

  1. Jika belum pernah menggunakan Batch, baca Mulai menggunakan Batch dan aktifkan Batch dengan menyelesaikan prasyarat untuk project dan pengguna.
  2. Buat atau identifikasi topik Pub/Sub untuk notifikasi Batch.
  3. Konfigurasi langganan untuk menerima dan menggunakan notifikasi.

Peran yang diperlukan

Membuat dan menjalankan tugas yang mengirim notifikasi

Anda dapat membuat tugas Batch yang mengirim notifikasi Pub/Sub dengan melakukan hal berikut:

gcloud

Gunakan Google Cloud CLI untuk membuat tugas yang menyertakan kolom notifications dan satu atau beberapa jobNotification objek di isi utama file JSON:

{
...
  "notifications": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "message": {
        ATTRIBUTES
      }
    }
  ]
...
}

Ganti kode berikut:

  • PROJECT_ID: project ID project yang berisi topik Pub/Sub.
  • TOPIC_ID: ID topik Pub/Sub dari topik yang Anda buat saat mengaktifkan notifikasi Pub/Sub.
  • ATTRIBUTES: tentukan satu atau beberapa atribut berikut, yang masing-masing memungkinkan Anda menerima notifikasi tentang status tugas atau semua tugasnya.

    • Untuk notifikasi tentang semua perubahan status tugas, tentukan hal berikut:

      "type": "JOB_STATE_CHANGED"
      
    • Untuk notifikasi tentang perubahan status tugas tertentu, tentukan hal berikut:

      "type": "JOB_STATE_CHANGED",
      "newJobState": "JOB_STATE"
      

      Ganti JOB_STATE dengan salah satu status tugas berikut:

      • QUEUED
      • SCHEDULED
      • RUNNING
      • SUCCEEDED
      • FAILED

      Untuk mengetahui informasi selengkapnya tentang status tugas, lihat Siklus proses tugas.

    • Untuk notifikasi tentang semua perubahan status tugas, tentukan hal berikut:

      "type": "TASK_STATE_CHANGED"
      
    • Untuk notifikasi tentang perubahan status tugas tertentu, tentukan hal berikut:

      "type": "TASK_STATE_CHANGED",
      "newTaskState": "TASK_STATE"
      

      Ganti TASK_STATE dengan salah satu status tugas berikut:

      • PENDING
      • ASSIGNED
      • RUNNING
      • SUCCEEDED
      • FAILED

      Untuk mengetahui informasi selengkapnya tentang status tugas, lihat Siklus proses tugas.

Misalnya, Anda ingin menerima notifikasi tentang semua perubahan status tugas dan setiap kali tugas gagal. Untuk melakukannya, Anda dapat memiliki file konfigurasi JSON yang mirip dengan berikut ini:

{
  "taskGroups": [
    {
      "taskSpec": {
        "runnables": [
          {
            "script": {
              "text": "echo Hello World! This is task $BATCH_TASK_INDEX."
            }
          }
        ]
      },
      "taskCount": 3,
    }
  ],
  "logsPolicy": {
      "destination": "CLOUD_LOGGING"
  },
  "notifications": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "message": {
        "type": "JOB_STATE_CHANGED"
      }
    },
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "message": {
        "type": "TASK_STATE_CHANGED",
        "newTaskState": "FAILED"
      }
    }
  ]
}

API

Gunakan REST API untuk membuat tugas yang menyertakan kolom notifications dan satu atau beberapa jobNotification objek di isi utama file JSON:

{
...
  "notifications": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "message": {
        ATTRIBUTES
      }
    }
  ]
...
}

Ganti kode berikut:

  • PROJECT_ID: project ID project yang berisi topik Pub/Sub.
  • TOPIC_ID: ID topik Pub/Sub dari topik yang Anda buat saat mengaktifkan notifikasi Pub/Sub.
  • ATTRIBUTES: tentukan satu atau beberapa atribut berikut, yang masing-masing memungkinkan Anda menerima notifikasi tentang status tugas atau semua tugasnya.

    • Untuk notifikasi tentang semua perubahan status tugas, tentukan hal berikut:

      "type": "JOB_STATE_CHANGED"
      
    • Untuk notifikasi tentang perubahan status tugas tertentu, tentukan hal berikut:

      "type": "JOB_STATE_CHANGED",
      "newJobState": "JOB_STATE"
      

      Ganti JOB_STATE dengan salah satu status tugas berikut:

      • QUEUED
      • SCHEDULED
      • RUNNING
      • SUCCEEDED
      • FAILED

      Untuk mengetahui informasi selengkapnya tentang status tugas, lihat Siklus proses tugas.

    • Untuk notifikasi tentang semua perubahan status tugas, tentukan hal berikut:

      "type": "TASK_STATE_CHANGED"
      
    • Untuk notifikasi tentang perubahan status tugas tertentu, tentukan hal berikut:

      "type": "TASK_STATE_CHANGED",
      "newTaskState": "TASK_STATE"
      

      Ganti TASK_STATE dengan salah satu status tugas berikut:

      • PENDING
      • ASSIGNED
      • RUNNING
      • SUCCEEDED
      • FAILED

      Untuk mengetahui informasi selengkapnya tentang status tugas, lihat Siklus proses tugas.

Misalnya, Anda ingin menerima notifikasi tentang semua perubahan status tugas dan setiap kali tugas gagal. Untuk melakukannya, Anda dapat memiliki file konfigurasi JSON yang mirip dengan berikut ini:

{
  "taskGroups": [
    {
      "taskSpec": {
        "runnables": [
          {
            "script": {
              "text": "echo Hello World! This is task $BATCH_TASK_INDEX."
            }
          }
        ]
      },
      "taskCount": 3,
    }
  ],
  "logsPolicy": {
      "destination": "CLOUD_LOGGING"
  },
  "notifications": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "message": {
        "type": "JOB_STATE_CHANGED"
      }
    },
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "message": {
        "type": "TASK_STATE_CHANGED",
        "newTaskState": "FAILED"
      }
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job with configured notifications
func createJobWithNotifications(w io.Writer, projectID, region, jobName, topicName string) (*batchpb.Job, error) {

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

	script := &batchpb.Runnable_Script_{
		Script: &batchpb.Runnable_Script{
			Command: &batchpb.Runnable_Script_Text{
				Text: "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.",
			},
		},
	}

	taskSpec := &batchpb.TaskSpec{
		ComputeResource: &batchpb.ComputeResource{
			// CpuMilli is milliseconds per cpu-second. This means the task requires 2 whole CPUs.
			CpuMilli:  2000,
			MemoryMib: 16,
		},
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
		Runnables: []*batchpb.Runnable{{
			Executable: script,
		}},
	}

	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	labels := map[string]string{"env": "testing", "type": "container"}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// In this case, we tell the system to use "e2-standard-4" machine type.
	// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "e2-standard-4",
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	notifications := []*batchpb.JobNotification{
		{
			PubsubTopic: fmt.Sprintf("projects/%s/topics/%s", projectID, topicName),
			Message: &batchpb.JobNotification_Message{
				Type: batchpb.JobNotification_JOB_STATE_CHANGED,
			},
		},
		{
			PubsubTopic: fmt.Sprintf("projects/%s/topics/%s", projectID, topicName),
			Message: &batchpb.JobNotification_Message{
				Type:         batchpb.JobNotification_TASK_STATE_CHANGED,
				NewTaskState: batchpb.TaskStatus_FAILED,
			},
		},
	}

	job := &batchpb.Job{
		Name:             jobName,
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           labels,
		Notifications:    notifications,
		LogsPolicy:       logsPolicy,
	}

	request := &batchpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID