ארגון משאבים באמצעות תוויות

במאמר הזה מוסבר איך להשתמש בתוויות כדי לארגן את המשאבים של Batch.

תוויות הן צמדי מפתח/ערך שמוחלים על משאבים כדי לקבץ ולתאר אותם. ל-Batch יש תוויות מוגדרות מראש שמוחלות באופן אוטומטי על משאבים, ותוויות בהתאמה אישית שאפשר להגדיר ולהחיל כשיוצרים משימה.

התוויות מאפשרות לסנן את התוצאות של רשימות המשאבים ודוחות החיוב ב-Cloud. לדוגמה, אתם יכולים להשתמש בתוויות כדי:

  • הבהרה וארגון של רשימת המשימות בפרויקט.

  • כדי להבחין בין אובייקטים שאפשר להריץ במשימה, אפשר להשתמש בתוויות שמתארות את סוג הקונטיינר או הסקריפט שהם מציינים.

  • כדי לנתח את העלויות, אפשר לסנן את דוחות החיוב ב-Cloud לפי המשאבים שנוצרו על ידי Batch או לפי משימות ספציפיות.

למידע נוסף על תוויות, אפשר לעיין גם במאמרי העזרה של Compute Engine בנושא תוויות.

לפני שמתחילים

  1. אם לא השתמשתם ב-Batch בעבר, כדאי לקרוא את המאמר תחילת השימוש ב-Batch ולהפעיל את Batch על ידי השלמת הדרישות המוקדמות לפרויקטים ולמשתמשים.
  2. כדי לקבל את ההרשאות שדרושות ליצירת משימה, צריך לבקש מהאדמין להקצות לכם את התפקידים הבאים ב-IAM:

    להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

    יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

הגבלות

בנוסף לדרישות לגבי תוויות שמפורטות במסמכי התיעוד של Compute Engine, יש כמה מגבלות על הוספת תוויות למשימות באצווה ולמשאבים שלהן:

  • אפשר להשתמש בתוויות ב-Batch רק למשאבים שנוצרו באמצעות Batch, מהסוגים הבאים:

  • אחרי שמתחשבים בתוויות המוגדרות מראש ש-Batch מחיל באופן אוטומטי על משימה, אפשר להגדיר את הכמויות הבאות של תוויות בהתאמה אישית:

    • אפשר להגדיר עד 63 תוויות בהתאמה אישית ולהחיל אותן על המשימה ועל האובייקטים שאפשר להריץ.

    • אפשר להגדיר עד 61 תוויות בהתאמה אישית לכל GPU, דיסק אחסון מתמיד (persistent disk) ו-VM שנוצרו בשביל המשימה.

  • ב-Batch אפשר להגדיר תוויות בהתאמה אישית רק עם שמות ייחודיים. ההשלכות של זה הן:

    • ניסיון לשנות תווית מוגדרת מראש גורם לשגיאות.

    • אם מגדירים תווית מותאמת אישית כפולה, היא מבטלת את התווית המותאמת אישית הקיימת.

  • ב-Batch אפשר להגדיר תוויות רק כשיוצרים משימה.

    • אי אפשר להוסיף, לעדכן או להסיר תוויות של משימות ושל אובייקטים שאפשר להריץ.

    • אפשר להשתמש ב-Compute Engine כדי להוסיף, לעדכן או להסיר תוויות של הדיסקים הקבועים והמכונות הווירטואליות שנוצרו בשביל המשימות, אבל זה לא מומלץ. אי אפשר להעריך באופן מהימן את מסגרת הזמן שבה המשאבים של משימה קיימים, ויכול להיות ששינויים לא יפעלו כמו שצריך עם Batch.

  • כדי לסנן את רשימת המשימות לפי תוויות, צריך לצפות ברשימת המשימות באמצעות ה-CLI של gcloud או Batch API.

תוויות שהוגדרו מראש

לכל תווית מוגדרת מראש יש מפתח שמתחיל בקידומת batch-. כברירת מחדל, Batch מחיל באופן אוטומטי את התוויות הבאות שהוגדרו מראש:

  • לכל משימה שיוצרים:

    • ‫batch-job-id: הערך של התווית הזו מוגדר לשם המשימה.
  • לכל GPU, דיסק לאחסון מתמיד ו-VM שנוצרו בשביל משימה:

    • ‫batch-job-id: הערך של התווית הזו מוגדר לשם המשימה.

    • ‫batch-job-uid: הערך של התווית הזו מוגדר למזהה הייחודי (UID) של המשימה.

    • ‫batch-node: הערך של התווית הזו הוא null – היא רק מקבצת את כל ה-GPUs, דיסקי האחסון המתמידים (persistent disks) והמכונות הווירטואליות שנוצרו בשביל המשימות. לדוגמה, תוכלו להשתמש בתווית הזו כשאתם צופים בדוח חיוב ב-Cloud כדי לזהות את העלויות של כל ה-GPUs, דיסקי האחסון המתמידים (persistent disks) וה-VMs שנוצרו על ידי Batch.

הגדרת תוויות מותאמות אישית

כשיוצרים משימה, אפשר להגדיר תווית מותאמת אישית אחת או יותר. אתם יכולים להגדיר תוויות בהתאמה אישית עם מפתחות חדשים או עם מפתחות שכבר נמצאים בשימוש בפרויקט. כדי להגדיר תוויות בהתאמה אישית, בוחרים אחת או יותר מהשיטות הבאות במסמך הזה, בהתאם למטרת התווית:

  • הגדרת תוויות בהתאמה אישית למשימה ולמשאבים שלה.

    בקטע הזה מוסבר איך להחיל תווית מותאמת אישית אחת או יותר על המשימה ועל כל GPU, דיסק קבוע ומכונה וירטואלית שנוצרו בשביל המשימה. אחרי שיוצרים את המשימה, אפשר להשתמש בתוויות האלה כדי לסנן את דוחות החיוב ב-Cloud ואת רשימות המשימות, דיסקי האחסון המתמידים (persistent disks) והמכונות הווירטואליות של הפרויקט.

  • הגדרת תוויות בהתאמה אישית למשימה.

    בקטע הזה מוסבר איך להחיל על המשימה תווית מותאמת אישית אחת או יותר. אחרי שיוצרים את המשימה, אפשר להשתמש בתוויות האלה כדי לסנן את רשימות המשימות של הפרויקט.

  • הגדרת תוויות בהתאמה אישית לאובייקטים שאפשר להריץ.

    בקטע הזה מוסבר איך להחיל תווית מותאמת אישית אחת או יותר על אובייקט אחד או יותר שאפשר להריץ בשביל המשימה. אחרי שיוצרים את המשימה, אפשר להשתמש בתוויות האלה כדי לסנן את רשימות המשימות של הפרויקט.

הגדרת תוויות בהתאמה אישית למשימה ולמשאבים שלה

התוויות שמוגדרות בשדה labels במדיניות ההקצאה של המשימה חלות על המשימה, וגם על כל GPU (אם יש), דיסק קבוע (כל דיסקי האתחול וכל נפחי האחסון החדשים) ומכונה וירטואלית שנוצרו בשביל המשימה.

כשיוצרים משימה באמצעות ה-CLI של gcloud או Batch API, אפשר להגדיר תוויות למשימה ולמשאבים שלה.

gcloud

לדוגמה, כדי ליצור משימת קונטיינר בסיסית ב-us-central1 שמגדירה שתי תוויות בהתאמה אישית שחלות על המשימה ועל המשאבים שנוצרו בשבילה:

  1. יוצרים קובץ JSON שמציין את פרטי ההגדרות של המשימה ואת השדה allocationPolicy.labels.

    {
      "allocationPolicy": {
        "instances": [
          {
            "policy": {
              "machineType": "e2-standard-4"
            }
          }
        ],
        "labels": {
          "VM_LABEL_NAME1": "VM_LABEL_VALUE1",
          "VM_LABEL_NAME2": "VM_LABEL_VALUE2"
        }
      },
      "taskGroups": [
        {
          "taskSpec": {
            "runnables": [
              {
                "container": {
                  "imageUri": "gcr.io/google-containers/busybox",
                  "entrypoint": "/bin/sh",
                  "commands": [
                    "-c",
                    "echo Hello world!"
                  ]
                }
              }
            ]
          }
        }
      ]
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ‫VM_LABEL_NAME1: השם של התווית הראשונה שרוצים להוסיף למכונות הווירטואליות שנוצרו בשביל המשימה.

    • ‫VM_LABEL_VALUE1: הערך של התווית הראשונה שתוחל על המכונות הווירטואליות שנוצרו בשביל המשימה.

    • ‫VM_LABEL_NAME2: השם של התווית השנייה שרוצים להוסיף למכונות הווירטואליות שנוצרו בשביל המשימה.

    • ‫VM_LABEL_VALUE2: הערך של התווית השנייה שרוצים להוסיף למכונות הווירטואליות שנוצרו בשביל המשימה.

  2. יוצרים את המשימה ב-us-central1 באמצעות הפקודה gcloud batch jobs submit.

    gcloud batch jobs submit example-job \
        --config=JSON_CONFIGURATION_FILE \
        --location=us-central1
    

    מחליפים את JSON_CONFIGURATION_FILE בנתיב לקובץ ה-JSON עם פרטי ההגדרות של המשימה שיצרתם בשלב הקודם.

API

לדוגמה, כדי ליצור משימת קונטיינר בסיסית ב-us-central1 שמגדירה שתי תוויות בהתאמה אישית שחלות על המשימה ועל המשאבים שנוצרו בשבילה, שולחים בקשת POST לmethod‏ jobs.create ומציינים את השדה allocationPolicy.labels.

POST https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?job_id=example-job

{
  "allocationPolicy": {
    "instances": [
      {
        "policy": {
          "machineType": "e2-standard-4"
        }
      }
    ],
    "labels": {
      "VM_LABEL_NAME1": "VM_LABEL_VALUE1",
      "VM_LABEL_NAME2": "VM_LABEL_VALUE2"
    }
  },
  "taskGroups": [
    {
      "taskSpec": {
        "runnables": [
          {
            "container": {
              "imageUri": "gcr.io/google-containers/busybox",
              "entrypoint": "/bin/sh",
              "commands": [
                "-c",
                "echo Hello world!"
              ]
            }
          }
        ]
      }
    }
  ]
}

מחליפים את מה שכתוב בשדות הבאים:

  • ‫VM_LABEL_NAME1: השם של התווית הראשונה שתוצמד למכונות הווירטואליות שנוצרו בשביל המשימה.

  • ‫VM_LABEL_VALUE1: הערך של התווית הראשונה שתוחל על המכונות הווירטואליות שנוצרו בשביל המשימה.

  • ‫VM_LABEL_NAME2: השם של התווית השנייה שרוצים להוסיף למכונות הווירטואליות שנוצרו בשביל המשימה.

  • ‫VM_LABEL_VALUE2: הערך של התווית השנייה שרוצים להוסיף למכונות הווירטואליות שנוצרו בשביל המשימה.

Java


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateBatchAllocationPolicyLabel {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "us-central1";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "example-job";
    // Name of the label1 to be applied for your Job.
    String labelName1 = "VM_LABEL_NAME1";
    // Value for the label1 to be applied for your Job.
    String labelValue1 = "VM_LABEL_VALUE1";
    // Name of the label2 to be applied for your Job.
    String labelName2 = "VM_LABEL_NAME2";
    // Value for the label2 to be applied for your Job.
    String labelValue2 = "VM_LABEL_VALUE2";

    createBatchAllocationPolicyLabel(projectId, region, jobName, labelName1,
        labelValue1, labelName2, labelValue2);
  }

  // This method shows how to create a job with labels defined 
  // in the labels field of a job's allocation policy. These are 
  // applied to the job, as well as to each GPU (if any), persistent disk 
  // (all boot disks and any new storage volumes), and VM created for the job.
  public static Job createBatchAllocationPolicyLabel(String projectId, String region,
                               String jobName, String labelName1,
                               String labelValue1, String labelName2, String labelValue2)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setContainer(
                  Runnable.Container.newBuilder()
                      .setImageUri("gcr.io/google-containers/busybox")
                      .setEntrypoint("/bin/sh")
                      .addCommands("-c")
                      .addCommands(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      .build())
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(2000)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(1).setTaskSpec(task).build();

      // 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.InstancePolicy instancePolicy =
          AllocationPolicy.InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(AllocationPolicy.InstancePolicyOrTemplate.newBuilder()
                  .setPolicy(instancePolicy)
                  .build())
              // Labels and their value to be applied to the job and its resources
              .putLabels(labelName1, labelValue1)
              .putLabels(labelName2, labelValue2)
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(LogsPolicy.newBuilder()
                      .setDestination(LogsPolicy.Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }

}

Node.js

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

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-labels-allocation-job';
// Name of the label1 to be applied for your Job.
const labelName1 = 'vm_label_name_1';
// Value for the label1 to be applied for your Job.
const labelValue1 = 'vmLabelValue1';
// Name of the label2 to be applied for your Job.
const labelName2 = 'vm_label_name_2';
// Value for the label2 to be applied for your Job.
const labelValue2 = 'vmLabelValue2';

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  script: new batch.Runnable.Script({
    commands: ['-c', 'echo Hello world! This is task ${BATCH_TASK_INDEX}.'],
  }),
});

// Specify what resources are requested by each task.
const computeResource = new batch.ComputeResource({
  // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
  cpuMilli: 500,
  // In MiB.
  memoryMib: 16,
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  computeResource,
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

// 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
const instancePolicy = new batch.AllocationPolicy.InstancePolicy({
  machineType: 'e2-standard-4',
});

const allocationPolicy = new batch.AllocationPolicy({
  instances: [{policy: instancePolicy}],
});
// Labels and their value to be applied to the job and its resources.
allocationPolicy.labels[labelName1] = labelValue1;
allocationPolicy.labels[labelName2] = labelValue2;

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  labels: {env: 'testing', type: 'script'},
  allocationPolicy,
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchLabelsAllocation() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchLabelsAllocation();

Python

from google.cloud import batch_v1


def create_job_with_custom_allocation_policy_labels(
    project_id: str, region: str, job_name: str, labels: dict
) -> batch_v1.Job:
    """
    This method shows the creation of a Batch job with custom labels which describe the allocation policy.
    Args:
        project_id (str): project ID or project number of the Cloud project you want to use.
        region (str): name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/locations
        job_name (str): the name of the job that will be created.
        labels (dict): a dictionary of key-value pairs that will be used as labels
            E.g., {"label_key1": "label_value2", "label_key2": "label_value2"}
    Returns:
        batch_v1.Job: The created Batch job object containing configuration details.
    """
    client = batch_v1.BatchServiceClient()

    runnable = batch_v1.Runnable()
    runnable.container = batch_v1.Runnable.Container()
    runnable.container.image_uri = "gcr.io/google-containers/busybox"
    runnable.container.entrypoint = "/bin/sh"
    runnable.container.commands = [
        "-c",
        "echo Hello world!",
    ]

    # Create a task specification and assign the runnable and volume to it
    task = batch_v1.TaskSpec()
    task.runnables = [runnable]

    # Specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Create a task group and assign the task specification to it
    group = batch_v1.TaskGroup()
    group.task_count = 3
    group.task_spec = task

    # 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
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    # Assign the provided labels to the allocation policy
    allocation_policy.labels = labels

    # Create the job and assign the task group and allocation policy to it
    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy

    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    # Create the job request and set the job and job ID
    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

הגדרת תוויות בהתאמה אישית למשימה

תוויות שמוגדרות בשדה labels של המשימה חלות רק על המשימה.

אתם יכולים להגדיר תוויות למשימה כשאתם יוצרים משימה באמצעות ה-CLI של gcloud או Batch API.

gcloud

לדוגמה, כדי ליצור משימת קונטיינר בסיסית ב-us-central1 שמגדירה שתי תוויות בהתאמה אישית שחלות על המשימה עצמה, מבצעים את השלבים הבאים:

  1. יוצרים קובץ JSON שמציין את פרטי ההגדרות של המשימה ואת השדה labels.

    {
      "taskGroups": [
        {
          "taskSpec": {
            "runnables": [
              {
                "container": {
                  "imageUri": "gcr.io/google-containers/busybox",
                  "entrypoint": "/bin/sh",
                  "commands": [
                    "-c",
                    "echo Hello World!"
                  ]
                }
              }
            ]
          }
        }
      ],
      "labels": {
        "JOB_LABEL_NAME1": "JOB_LABEL_VALUE1",
        "JOB_LABEL_NAME2": "JOB_LABEL_VALUE2"
      }
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ‫JOB_LABEL_NAME1: השם של התווית הראשונה שרוצים להוסיף למשימה.

    • ‫JOB_LABEL_VALUE1: הערך של התווית הראשונה שרוצים להוסיף למשימה.

    • ‫JOB_LABEL_NAME2: השם של התווית השנייה שרוצים להוסיף למשימה.

    • ‫JOB_LABEL_VALUE2: הערך של התווית השנייה שרוצים להוסיף למשימה.

  2. יוצרים את המשימה ב-us-central1 באמצעות הפקודה gcloud batch jobs submit עם הדגלים הבאים:

    gcloud batch jobs submit example-job \
        --config=JSON_CONFIGURATION_FILE \
        --location=us-central1
    

    מחליפים את JSON_CONFIGURATION_FILE בנתיב לקובץ ה-JSON עם פרטי ההגדרות של המשימה שיצרתם בשלב הקודם.

API

לדוגמה, כדי ליצור משימת מאגר ב-us-central1 שמגדירה שתי תוויות בהתאמה אישית שיוחלו על המשימות עצמן, שולחים בקשת POST אל ה-method‏ jobs.create ומציינים את השדה labels.

POST https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?job_id=example-job

{
  "taskGroups": [
    {
      "taskSpec": {
        "runnables": [
          {
            "container": {
              "imageUri": "gcr.io/google-containers/busybox",
              "entrypoint": "/bin/sh",
              "commands": [
                "-c",
                "echo Hello World!"
              ]
            }
          }
        ]
      }
    }
  ],
  "labels": {
    "JOB_LABEL_NAME1": "JOB_LABEL_VALUE1",
    "JOB_LABEL_NAME2": "JOB_LABEL_VALUE2"
  }
}

מחליפים את מה שכתוב בשדות הבאים:

  • ‫JOB_LABEL_NAME1: השם של התווית הראשונה שרוצים להחיל על המשימה.

  • ‫JOB_LABEL_VALUE1: הערך של התווית הראשונה שרוצים להוסיף למשימה.

  • ‫JOB_LABEL_NAME2: השם של התווית השנייה שרוצים להחיל על המשימה.

  • ‫JOB_LABEL_VALUE2: הערך של התווית השנייה שרוצים להוסיף למשימה.

Java


import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


public class CreateBatchLabelJob {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "us-central1";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "example-job";
    // Name of the label1 to be applied for your Job.
    String labelName1 = "JOB_LABEL_NAME1";
    // Value for the label1 to be applied for your Job.
    String labelValue1 = "JOB_LABEL_VALUE1";
    // Name of the label2 to be applied for your Job.
    String labelName2 = "JOB_LABEL_NAME2";
    // Value for the label2 to be applied for your Job.
    String labelValue2 = "JOB_LABEL_VALUE2";

    createBatchLabelJob(projectId, region, jobName, labelName1,
        labelValue1, labelName2, labelValue2);
  }

  // Creates a job with labels defined in the labels field.
  public static Job createBatchLabelJob(String projectId, String region, String jobName,
                    String labelName1, String labelValue1, String labelName2, String labelValue2)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setContainer(
                  Runnable.Container.newBuilder()
                      .setImageUri("gcr.io/google-containers/busybox")
                      .setEntrypoint("/bin/sh")
                      .addCommands("-c")
                      .addCommands(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      .build())
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(2000)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(1).setTaskSpec(task).build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(LogsPolicy.newBuilder()
              .setDestination(LogsPolicy.Destination.CLOUD_LOGGING).build())
              // Labels and their value to be applied to the job.
              .putLabels(labelName1, labelValue1)
              .putLabels(labelName2, labelValue2)
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }

}

Node.js

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

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-labels-job';
// Name of the label1 to be applied for your Job.
const labelName1 = 'job_label_name_1';
// Value for the label1 to be applied for your Job.
const labelValue1 = 'job_label_value1';
// Name of the label2 to be applied for your Job.
const labelName2 = 'job_label_name_2';
// Value for the label2 to be applied for your Job.
const labelValue2 = 'job_label_value2';

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  container: new batch.Runnable.Container({
    imageUri: 'gcr.io/google-containers/busybox',
    entrypoint: '/bin/sh',
    commands: ['-c', 'echo Hello world! This is task ${BATCH_TASK_INDEX}.'],
  }),
});

// Specify what resources are requested by each task.
const computeResource = new batch.ComputeResource({
  // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
  cpuMilli: 500,
  // In MiB.
  memoryMib: 16,
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  computeResource,
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});

// Labels and their value to be applied to the job and its resources.
job.labels[labelName1] = labelValue1;
job.labels[labelName2] = labelValue2;

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchLabelsJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchLabelsJob();

Python

from google.cloud import batch_v1


def create_job_with_custom_job_labels(
    project_id: str,
    region: str,
    job_name: str,
    labels: dict,
) -> batch_v1.Job:
    """
    This method creates a Batch job with custom labels.
    Args:
        project_id (str): project ID or project number of the Cloud project you want to use.
        region (str): name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/locations
        job_name (str): the name of the job that will be created.
        labels (dict): A dictionary of custom labels to be added to the job.
            E.g., {"label_key1": "label_value2", "label_key2": "label_value2"}
    Returns:
        batch_v1.Job: The created Batch job object containing configuration details.
    """
    client = batch_v1.BatchServiceClient()

    runnable = batch_v1.Runnable()
    runnable.container = batch_v1.Runnable.Container()
    runnable.container.image_uri = "gcr.io/google-containers/busybox"
    runnable.container.entrypoint = "/bin/sh"
    runnable.container.commands = [
        "-c",
        "echo Hello world!",
    ]

    # Create a task specification and assign the runnable and volume to it
    task = batch_v1.TaskSpec()
    task.runnables = [runnable]

    # Specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Create a task group and assign the task specification to it
    group = batch_v1.TaskGroup()
    group.task_count = 3
    group.task_spec = task

    # 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
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    # Create the job and assign the task group and allocation policy to it
    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy

    # Set the labels for the job
    job.labels = labels

    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    # Create the job request and set the job and job ID
    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

הגדרת תוויות בהתאמה אישית לאובייקטים שאפשר להריץ

תוויות שמוגדרות בשדה labels של אובייקט שאפשר להריץ חלות רק על האובייקט הזה.

כשיוצרים משימה באמצעות ה-CLI של gcloud או Batch API, אפשר להגדיר תוויות לאובייקט אחד או יותר שאפשר להריץ.

gcloud

לדוגמה, כדי ליצור משימה ב-us-central1 שמגדירה שתי תוויות בהתאמה אישית, תווית אחת לכל אחד משני האובייקטים שאפשר להריץ במשימה, מבצעים את השלבים הבאים:

  1. יוצרים קובץ JSON שמציין את פרטי ההגדרות של המשימה ואת השדות של runnables.labels.

    {
      "taskGroups": [
        {
          "taskSpec": {
            "runnables": [
              {
                "container": {
                  "imageUri": "gcr.io/google-containers/busybox",
                  "entrypoint": "/bin/sh",
                  "commands": [
                    "-c",
                    "echo Hello from task ${BATCH_TASK_INDEX}!"
                  ]
                },
                "labels": {
                  "RUNNABLE1_LABEL_NAME1": "RUNNABLE1_LABEL_VALUE1"
                }
              },
              {
                "script": {
                  "text": "echo Hello from task ${BATCH_TASK_INDEX}!"
                },
                "labels": {
                  "RUNNABLE2_LABEL_NAME1": "RUNNABLE2_LABEL_VALUE1"
                }
              }
            ]
          }
        }
      ]
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • ‫RUNNABLE1_LABEL_NAME1: שם התווית שרוצים להוסיף לאובייקט הראשון שאפשר להריץ במשימה.

    • ‫RUNNABLE1_LABEL_VALUE1: הערך של התווית שרוצים להוסיף לאובייקט הראשון שאפשר להריץ במשימה.

    • ‫RUNNABLE2_LABEL_NAME1: שם התווית שרוצים להחיל על האובייקט השני שאפשר להריץ במשימה.

    • ‫RUNNABLE2_LABEL_VALUE1: הערך של התווית שרוצים להוסיף לאובייקט השני שאפשר להריץ במשימה.

  2. יוצרים את המשימה ב-us-central1 באמצעות הפקודה gcloud batch jobs submit.

    gcloud batch jobs submit example-job \
        --config=JSON_CONFIGURATION_FILE \
        --location=us-central1
    

    מחליפים את JSON_CONFIGURATION_FILE בנתיב לקובץ ה-JSON עם פרטי ההגדרות של המשימה שיצרתם בשלב הקודם.

API

לדוגמה, כדי ליצור משימה ב-us-central1 שמגדירה שתי תוויות בהתאמה אישית, אחת לכל אחד משני האובייקטים שאפשר להריץ של המשימה, שולחים בקשת POST לשיטה jobs.create ומציינים את השדות runnables.labels.

POST https://batch.googleapis.com/v1/projects/example-project/locations/us-central1/jobs?job_id=example-job

{
  "taskGroups": [
    {
      "taskSpec": {
        "runnables": [
          {
            "container": {
              "imageUri": "gcr.io/google-containers/busybox",
              "entrypoint": "/bin/sh",
              "commands": [
                "-c",
                "echo Hello from ${BATCH_TASK_INDEX}!"
              ]
            },
            "labels": {
              "RUNNABLE1_LABEL_NAME1": "RUNNABLE1_LABEL_VALUE1"
            }
          },
          {
            "script": {
              "text": "echo Hello from ${BATCH_TASK_INDEX}!"
            },
            "labels": {
              "RUNNABLE2_LABEL_NAME1": "RUNNABLE2_LABEL_VALUE1"
            }
          }
        ]
      }
    }
  ]
}

מחליפים את מה שכתוב בשדות הבאים:

  • ‫RUNNABLE1_LABEL_NAME1: השם של התווית שרוצים להוסיף לאובייקט שאפשר להריץ של המשימה הראשונה.

  • ‫RUNNABLE1_LABEL_VALUE1: הערך של התווית שרוצים להוסיף לאובייקט שאפשר להריץ של המשימה הראשונה.

  • ‫RUNNABLE2_LABEL_NAME1: שם התווית שרוצים להוסיף לאובייקט שאפשר להריץ של המשימה השנייה.

  • ‫RUNNABLE2_LABEL_VALUE1: הערך של התווית שרוצים להוסיף לאובייקט שאפשר להריץ של המשימה השנייה.

Java


import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateBatchRunnableLabel {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "us-central1";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "example-job";
    // Name of the label1 to be applied for your Job.
    String labelName1 = "RUNNABLE_LABEL_NAME1";
    // Value for the label1 to be applied for your Job.
    String labelValue1 = "RUNNABLE_LABEL_VALUE1";
    // Name of the label2 to be applied for your Job.
    String labelName2 = "RUNNABLE_LABEL_NAME2";
    // Value for the label2 to be applied for your Job.
    String labelValue2 = "RUNNABLE_LABEL_VALUE2";

    createBatchRunnableLabel(projectId, region, jobName, labelName1,
        labelValue1, labelName2, labelValue2);
  }

  // Creates a job with labels defined in the labels field
  // for a runnable. The labels are only applied to that runnable.
  // In Batch, a runnable represents a single task or unit of work within a job.
  // It can be a container (like a Docker image) or a script.
  public static Job createBatchRunnableLabel(String projectId, String region, String jobName,
                   String labelName1, String labelValue1, String labelName2, String labelValue2)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setContainer(
                  Runnable.Container.newBuilder()
                      .setImageUri("gcr.io/google-containers/busybox")
                      .setEntrypoint("/bin/sh")
                      .addCommands("-c")
                      .addCommands(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                              + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      .build())
              // Label and its value to be applied to the container
              // that processes data from a specific region.
              .putLabels(labelName1, labelValue1)
              .setScript(Runnable.Script.newBuilder()
              .setText("echo Hello world! This is task ${BATCH_TASK_INDEX}. ").build())
              // Label and its value to be applied to the script
              // that performs some analysis on the processed data.
              .putLabels(labelName2, labelValue2)
              .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
              .setCpuMilli(2000)
              // In MiB.
              .setMemoryMib(2000)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(1).setTaskSpec(task).build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(LogsPolicy.newBuilder()
              .setDestination(LogsPolicy.Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run for the specific project.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }

}

Node.js

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

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'us-central1';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'example-job';
// Name of the label1 to be applied for your Job.
const labelName1 = 'RUNNABLE_LABEL_NAME1';
// Value for the label1 to be applied for your Job.
const labelValue1 = 'RUNNABLE_LABEL_VALUE1';
// Name of the label2 to be applied for your Job.
const labelName2 = 'RUNNABLE_LABEL_NAME2';
// Value for the label2 to be applied for your Job.
const labelValue2 = 'RUNNABLE_LABEL_VALUE2';

const container = new batch.Runnable.Container({
  imageUri: 'gcr.io/google-containers/busybox',
  entrypoint: '/bin/sh',
  commands: ['-c', 'echo Hello world! This is task ${BATCH_TASK_INDEX}.'],
});

const script = new batch.Runnable.Script({
  commands: ['-c', 'echo Hello world! This is task ${BATCH_TASK_INDEX}.'],
});

const runnable1 = new batch.Runnable({
  container,
  // Label and its value to be applied to the container
  // that processes data from a specific region.
  labels: {
    [labelName1]: labelValue1,
  },
});

const runnable2 = new batch.Runnable({
  script,
  // Label and its value to be applied to the script
  // that performs some analysis on the processed data.
  labels: {
    [labelName2]: labelValue2,
  },
});

// Specify what resources are requested by each task.
const computeResource = new batch.ComputeResource({
  // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
  cpuMilli: 500,
  // In MiB.
  memoryMib: 16,
});

const task = new batch.TaskSpec({
  runnables: [runnable1, runnable2],
  computeResource,
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchLabelsRunnable() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchLabelsRunnable();

Python

from google.cloud import batch_v1


def create_job_with_custom_runnables_labels(
    project_id: str,
    region: str,
    job_name: str,
    labels: dict,
) -> batch_v1.Job:
    """
    This method creates a Batch job with custom labels for runnable.
    Args:
        project_id (str): project ID or project number of the Cloud project you want to use.
        region (str): name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/locations
        job_name (str): the name of the job that will be created.
        labels (dict): a dictionary of key-value pairs that will be used as labels
            E.g., {"label_key1": "label_value2"}
    Returns:
        batch_v1.Job: The created Batch job object containing configuration details.
    """
    client = batch_v1.BatchServiceClient()

    runnable = batch_v1.Runnable()
    runnable.display_name = "Script 1"
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world from Script 1 for task ${BATCH_TASK_INDEX}"
    # Add custom labels to the first runnable
    runnable.labels = labels

    # Create a task specification and assign the runnable and volume to it
    task = batch_v1.TaskSpec()
    task.runnables = [runnable]

    # Specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Create a task group and assign the task specification to it
    group = batch_v1.TaskGroup()
    group.task_count = 3
    group.task_spec = task

    # 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
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    # Create the job and assign the task group and allocation policy to it
    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy

    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    # Create the job request and set the job and job ID
    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

המאמרים הבאים